我有一个使用UI路由器的Angular应用程序,我试图在应用程序运行时验证用户的令牌(如果存在).我还检查用户是否有权访问某些路线.问题是$stateChangeStart
在我从授权端点收到响应之前正在运行.这是一些代码(coffeescript与js下面) - 这都在我的run
块内.
app.run(($rootScope, $state, $stateParams, $log, Auth) -> currentState = 'home' $rootScope.$state = $state # read a cookie if cookie exists if Auth.setAuthenticationToken() # hit api endpoint to validate token Auth.validateToken (user) -> # route to current state # this returns after $stateChangeStart runs below $state.go(currentState) $rootScope.$on '$stateChangeStart', (event, toState, toParams, fromState, fromParams) -> currentState = toState.name Auth.setAuthenticationToken() $rootScope.error = null # compare users access permissions with incoming route's access level if (!Auth.authorize toState.data.access, Auth.user) event.preventDefault() $rootScope.error = "Sorry, you haven't provided the required credentials." $log.warn $rootScope.error )
我的问题是如何$stateChangeStart
在返回auth端点的响应后才能运行.这只需要第一次发生.每次后续状态更改都可以在不命中auth端点的情况下完成.