I'm currently embarking on a new project, and for the initial phase, I want to verify if the user has an active session with the server by sending an XHR HEAD request to /api/me.
My objective is to implement the following syntax
$rootScope.$on("$routeChangeStart", function(event, current, previous, rejection){/*...*/})
The dilemma lies in not wanting to duplicate this code for every controller. Is there a way to achieve this in a more universal manner?, .run?, service(factory), what would be the best approach?.
If possible, provide a simple code snippet since I'm fairly inexperienced with this framework.
var app = angular.module('home', []);
var httpConfig = {withCredentials: true};
app.config(function($routeProvider){
$routeProvider.
when('/',
{
template: 'views/home.html',
controller: homeCtrl
}).
when('/login',
{
template: 'views/login.html',
controller: loginCtrl
}).
when('/logout',
{
template: 'views/logout.html',
controller: logoutCtrl
}).
otherwise(
{
template: 'views/home.html',
controller: homeCtrl
})
}).
run(function($rootScope, authUser){
$rootScope.$on('$routeChangeStart', function () {
authUser($rootScope);
})
}).
factory('authUser', function($http, httpConfig){
var promise = $http.head('/users/me', httpConfig);
})