Leong Sze Kim Leong Sze Kim - 1 month ago 4
AngularJS Question

Angular service unable to execute function

function loadUserCredentials() {
var token = new Object();
token.token = window.localStorage.getItem(LOCAL_TOKEN_KEY);
$http.post("http://localhost:8080/checkTokenValid",token).then(function(result){
console.log(result.data.success);
if(result.data.success){
useCredentials();
}
});
};


This
loadCredentials()
is loaded everytime the page refresh, I'm checking if it is authenticated at my
angular.run


controlApp.run(function ($location, $rootScope,controlProvider){
$rootScope.$on('$routeChangeStart',function(event,next,nextParems){
if (!controlProvider.isAuthenticated()){
$location.path('/login');
}
})
});


I think this is running before
loadCredentials
complete, so I always get login page. Is there any way I can delay the
angular.run
? So that I can have my
loadCredentials
to check is the user having the valid token.

Answer

Yes you can do that by $timeout :

controlApp.run(function ($location, $rootScope, controlProvider, $timeout) {
    $rootScope.$on('$routeChangeStart', function (event, next, nextParems) {
        $timeout(function () {
            if (!controlProvider.isAuthenticated()) {
                $location.path('/login');
            }
        }, 500);
    })
});
Comments