如何将routeProvider代码更改为stateProvider(ui-router)代码?

时间:2014-09-25 13:54:40

标签: angularjs

我有这段代码:

app.run(function($rootScope, $location, $window, AuthenticationService) {
        $rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
            //redirect only if both isAuthenticated is false and no token is set
            if (nextRoute != null && nextRoute.access != null && nextRoute.access.requiredAuthentication 
                && !AuthenticationService.isAuthenticated && !$window.sessionStorage.token) {

                $location.path("/admin/login");
            }
        });
    });

我知道我们有这些ui-router方法:$stateChangeStart, $stateChangeSuccess, $stateChangeError,但nextRoutecurrentRoute怎么样?

除了有一种方法可以在不使用.run()块的情况下实现上述目标吗?

供参考:https://raw.githubusercontent.com/kdelemme/blogjs/master/app/js/app.js

可能重复:AngularJS: ui-router secured states

1 个答案:

答案 0 :(得分:2)

这有效:

app.run(function($rootScope, $location, $window, AuthenticationService) {
    $rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){

        if (!AuthenticationService.isAuthenticated && toState.access.requiredAuthentication != false){
            console.debug("NO AUTH");
            event.preventDefault();
            $state.go('login');
        }
    });
});