2014-09-25 79 views
1

我有这样的代码:HowTo将routeProvider代码更改为stateProvider(ui-router)代码?

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路由器的方法:$stateChangeStart, $stateChangeSuccess, $stateChangeError,但如何nextRoutecurrentRoute

另外有没有一种方法实现上述不使用.run()块?

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

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

回答

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