2014-09-25 54 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'); 
     } 
    }); 
});