Leong Sze Kim
Leong Sze Kim

Reputation: 65

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.

Upvotes: 1

Views: 47

Answers (1)

Jigar7521
Jigar7521

Reputation: 1579

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);
    })
});

Upvotes: 2

Related Questions