我正在尝试构建我想在根状态解析上初始化的 Angular 色权限系统:
$stateProvider
.state('common', {
resolve:{
user: function(AclService, UserService) {
UserService.getCurrent().then((currentUser) => {
AclService.initialize(currentUser);
});
}
}
})
并且每次在 $stateChangeStart 上检查权限:
$rootScope.$on('$stateChangeStart', ($event, toState) => AclService.interceptStateChange($event, toState));
但我遇到了一个问题,即首先 $stateChangeStart 在 resolve 之前被触发,因此权限尚未初始化。
在这种情况下你会推荐什么?
最佳答案
您可以在应用的运行函数中执行此操作。这是我如何预先加载身份验证数据的简化版本。
(function() {
"use strict";
angular
.module("myModule", [ //dependencies here...]);
angular
.module("myModule")
.run(run);
run.$inject = ["$rootScope", "$state", "authService"];
function run($rootScope, $state, authService) {
authService.fillAuthData(); //front load auth stuff here...
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
var isPublic = (toState.data && toState.data.isPublic && toState.data.isPublic === true);
var requiredRole = (toState.data && toState.data.requiredRole) ? toState.data.requiredRole : null;
var authorized = isPublic || authService.isUserInRole(requiredRole);
if (authService.authentication.isAuth || isPublic) {
//if the user doesn't have the requisite permission to view the page, redirect them to an unauthorized page
if (!authorized) {
event.preventDefault();
$state.go("unauthorized");
return;
}
} else {
event.preventDefault();
$state.go("login");
return;
}
});
}
})();
状态定义可能如下所示:
.state("someState", {
url: "/someState",
templateUrl: "my/folder/file.html",
data: {
pageTitle: "Some Page",
isPublic: false,
requiredRole: "Admin"
}
})
关于javascript - 是否可以在触发 $stateChangeStart 之前解析某些数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35652567/