我有一个使用授权逻辑和UI路由的Angular应用程序,以禁止未经授权的用户访问某些状态/视图。我遵循监听stateChange事件的标准方法,这将触发我的授权逻辑。在可恶的页面重新加载之前,这一切都运作良好。
我将会话数据(包括授权状态)存储在本地存储中,以便在页面重新加载时,我可以使用ui-router中的父状态首先解析/获取本地存储中的授权状态,然后再尝试更改视图。下面是我的“app”父状态对象的配置:
我的问题在于
有什么想法吗?
顺便说一句,这里有一个类似的未得到答复的SO问题:延迟Angular UI Router $stateChangeStart,直到接收到服务器授权响应
我将会话数据(包括授权状态)存储在本地存储中,以便在页面重新加载时,我可以使用ui-router中的父状态首先解析/获取本地存储中的授权状态,然后再尝试更改视图。下面是我的“app”父状态对象的配置:
$stateProvider.
state('app', {
url: '/app',
abstract: true,
controller: 'appCtrl',
data: {
authorizedRoles: [USER_ROLES.all]
},
templateUrl: 'partials/app.html',
resolve: {
//Try to restore from the previous session before loading any of the app child states
RestoredSession: ['SessionService',
function(SessionService){
return SessionService.restoreSession();
}]
}
})
...various app. child states
这是我的 onStateChange 监听器代码:
//listen for a ui.router $stateChangeStart event and test the new path to see if the currentUser
//is authorized to view that page
.run( ['$rootScope', 'AUTH_EVENTS', 'SessionService',
function ($rootScope, AUTH_EVENTS, SessionService) {
$rootScope.$on('$stateChangeStart', function (event, next) {
var authorizedRoles = next.data.authorizedRoles;
//If the requested page allows guest access, then continue to stateChange
if (authorizedRoles.indexOf('guest') !== -1 || authorizedRoles.indexOf('*') !== -1) return;
//If the requested page requires authorization, check login and auth privileges
if (!SessionService.isAuthorized(authorizedRoles)) {
event.preventDefault();
if (SessionService.existingSession()) {
// user is not allowed
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
console.log("User attempted to access page for which he is not authorized");
} else {
// user is not logged in
$rootScope.$broadcast(AUTH_EVENTS.notLoggedIn);
console.log("User attempted to access page when he is not logged in");
}
}
});
}]);
我的问题在于
stateChangeStart
事件在app resolve
之前触发,这导致监听器停止状态更改(通过event.preventDefault
),然后我的resolve加载存储的会话数据,往往确定用户一直被授权。如果我可以在事件触发之前要求执行resolve,那么我就成功了。有什么想法吗?
顺便说一句,这里有一个类似的未得到答复的SO问题:延迟Angular UI Router $stateChangeStart,直到接收到服务器授权响应