Defer Angular UI Router $stateChangeStart until server authorization response receieved(推迟 Angular UI 路由器 $stateChangeStart 直到收到服务器授权响应)
问题描述
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
)
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.
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..
};
});
oh, sorry about no coffee
这篇关于推迟 Angular UI 路由器 $stateChangeStart 直到收到服务器授权响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:推迟 Angular UI 路由器 $stateChangeStart 直到收到服务器授权响应
基础教程推荐
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01