Waiting for $http before running angular spa

2019-06-05 03:20发布

问题:

I have a SPA using JWT (json web tokens) for authorization to the api. The problem is when they hit refresh on the browser after being logged in I need to verify the token is still valid via an ajax request and then continue loading the SPA. I added this to the .run() which kind of works, but since my navigation changes if they are logged in, the page loads before the token is verified, and looks wrong. I'm new to angular, but guess this could be done with a promise?

// handle refreshing browser
if ($window.sessionStorage.token && !AuthenticationService.isLogged()) {
    UserService.verify().success(function (data) {
        AuthenticationService.setLogged(true);
    }).error(function () {
         delete $window.sessionStorage.token;
         $state.transitionTo('app.login');
    });
}

回答1:

I was able to get this working with the following state setup:

$stateProvider
    .state('app', {
        abstract: true,
        url: '/',
        views: {
            root: {
                templateUrl: 'tpl/index.html'
            }
        },
        resolve: {
            User: ['$window', '$q', 'AuthenticationService', 'UserService' , function($window, $q, AuthenticationService, UserService) {
                if ($window.sessionStorage.token && !AuthenticationService.isLogged()) {
                    var d = $q.defer();
                    UserService.verify().success(function (data) {
                        AuthenticationService.setLogged(true);
                        d.resolve();
                    }).error(function () {
                        delete $window.sessionStorage.token;
                        d.resolve();
                    });
                    return d.promise;
                }
            }]
        }
    });


标签: angularjs jwt