我正在尝试构建角色权限系统,我想在root 州解决方案上初始化:
$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 ,因此权限尚未初始化。
在这种情况下你会推荐什么?
答案 0 :(得分:0)
您可以在应用的运行功能中执行此操作。这是我如何预先加载auth数据的精简版本。
(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"
}
})
答案 1 :(得分:0)
你不应该在状态结算中做一些auth逻辑。更好的方法是在angular.run函数中为$ stateChangeStart事件设置监听器:
angular.module('yourModule', [])
.run(['$rootScope', 'principal', '$state', function ($rootScope, principal, $state) {
var firstOpen = true;
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
if (!principal.isAuthenticated() && firstOpen) {
firstOpen = false;
event.preventDefault();
principal.checkAuthentication().then(function() {
$state.go(toState, toParams);
});
} else if (principal.isAuthenticated() && toState.name === 'login') {
event.preventDefault();
// Do some stuff here, for example, redirect to main page
}
});
}
]);