推迟 Angular UI Router $stateChangeStart 直到收到服务器授权响应 [英] Defer Angular UI Router $stateChangeStart until server authorization response receieved
问题描述
我有一个使用 UI 路由器的 Angular 应用程序,我试图在应用程序运行时验证用户的令牌(如果存在).我也在检查用户是否有权访问某些路线.问题是 $stateChangeStart
在我收到来自授权端点的响应之前正在运行.这是一些代码(下面是带有 js 的咖啡脚本) - 这一切都在我的 run
块中.
I have an Angular app using UI Router where I'm trying to validate a user's token, if one exists, when the app runs. I am also checking that the user has permission to access certains routes. The problem is that $stateChangeStart
is running before I receive the response back from the authorization endpoint. Here's some code (coffeescript with js below) - this is all within my run
block.
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 端点的情况下完成.
My question is how can I get the $stateChangeStart
to run only after the response from the auth endpoint has been returned. This only needs to happen the first time. Every subsequent state change can be done without hitting the auth endpoint.
推荐答案
我会在您的 Auth
服务中创建一个返回承诺的函数.稍后,解决(授权)或拒绝(未授权)推迟.然后在路由定义的 resolve
属性上使用它
I'd create a function in your Auth
service that returns a promise. Later, resolve (authorized) or reject (not authrized) that deferred. Then use it on the resolve
property of your route definitions
$stateProvider.state('stateName',{
...
...
resolve: {
isAuthorized: function(Auth){
return Auth.checkAuthorization();
}
}
})
为了支持后续检查,您可以在服务中维护承诺 这可能如下所示:
To support subsequent checks you could maintain a promise within the service This might look like:
myApp.service('Auth',function($http,$q){
var authStatusDeferred = $q.defer();
this.checkAuthorization = function(){
return authStatusDeferred.promise;
};
this.validateToken = function(user){
var isValid = false;
//..do validation stuff
if(isValid) authStatusDeferred.resolve();
//Otherwise state change will not happen..
};
});
哦,抱歉没喝咖啡
这篇关于推迟 Angular UI Router $stateChangeStart 直到收到服务器授权响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!