In an application made with AngularJS, some pages are protected by login.
I configured the module as follows:
var app = angular.module('App', ['ngRoute', 'ngTouch', 'mobile-angular-ui']);
app.config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.
//...
.when('/dashboard', {
title: 'Dashboard',
templateUrl: 'view/dashboard.html',
controller: 'authCtrl',
requireLogin: true
})
//...
$locationProvider.html5Mode(true);
}])
.run(function ($rootScope, $route, $location, Data, Session) {
$rootScope.$on('$locationChangeStart', function (event) {
var nextPath = $location.path();
var nextRoute = $route.routes[nextPath];
if (nextRoute.requireLogin && !Session.getUserAuthenticated()) {
$location.path("/login");
}
});
});
Notice that at the end of the code above, I have a service (Session.getUserAuthenticated ()) that checks if the user is logged in before changing the route, see the code:
app.service('Session', function($http) {
this.getUserAuthenticated = function() {
var auth = false;
$http.post('api/v1/session').then(function (results) {
if(results.data.uid) auth = true;
});
return auth;
};
});
The problem is that the above service always returns false, since it returns before the $ http.post response, how do I resolve the problem? Is it possible to wait for the POST response or is the logic I'm using is incorrect?