Thursday 28 January 2016

javascript - AngularJS: Promise in app.run() stuck in loop forever

I'm using app.run() in my AngularJS app to check whether a user is logged in before displaying the site to block access to various sites for non-registered users. I tried doing it with a promise because before, whenever I reloaded the page the isLoggedIn function would return false the getStatus hasn't returned the answer from the server yet.



Now using the promise, the site just calls itself in a loop forever, I guess because the process just repeats itself when the promise is resolved. Where am I going wrong and how could I fix this? Thanks in advance, help is much appreciated!




This is my code in app.js:



app.run(function($rootScope, $state, authService){
$rootScope.$on('$stateChangeStart', function(event, next, nextParams, from, fromParams){
event.preventDefault();
authService.getUserStatus().then(function(){
console.log(authService.isLoggedIn());
if(next.access.restricted && !authService.isLoggedIn()){
$state.go('index', {}, { reload: true });

} else {
$state.go(next, {}, { reload: true });
}
});
});
});


Here's the service authService.js:




(function(){
var app = angular.module('labelcms');
app.factory('authService', ['$q', '$timeout', '$http', function($q, $timeout, $http){

var user = null;

var isLoggedIn = function(){
if(user){
return true;
} else {

return false;
}
};

var getUserStatus = function(){
var deferred = $q.defer();

$http.get('/api/user/status')
.success(function(data){
if(data.status){

user = data.status;
deferred.resolve();
} else {
user = false;
deferred.resolve();
}
})
.error(function(data){
console.log('Error: ' + data);
user = false;

deferred.resolve();
});

return deferred.promise;
};

return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,

logout: logout,
signup: signup
});

}]);
})();

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...