文档中没有提到任何内容,但这是我实现它的方式。
基本上,我在 $rootScope 中有用户角色(当我从后端获取它们时)
1)在所有状态定义中定义所有用户都可以访问该状态。例子:
.state('state1', {
url: '/state1',
views: {
content: {
templateUrl: 'state1-partial.html',
controller: 'StateOneController'
}
},
data: {
access:['Admin','Manager'] //only admin and manager can access this state
}
})
.state('state2', {
url: '/state2',
views: {
content: {
templateUrl: 'state2-partial.html',
controller: 'StateTwoController'
}
},
data: {
access:['Admin'] //only admin can access this state
}
})
2)然后在 angular.module 运行函数中,当状态更改事件发生时,我访问这些:
此外,我在这里使用服务isAuthorized来验证用户是否有权访问该状态。如果是,我将用户导航到该状态,否则我会抛出错误。
angular.module('myApp').run(function($rootScope, $state,$stateParams,isAuthorized){
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState,fromParams) {
var isAccessRequired = toState.data.access;
var isAccessRequired = toState.data && toState.data.access;
//prevent default routing
if(isAccessRequired){
//I stored userRoles in $rootScope.userRole in an array when fetching from backend.
var hasAccess = isAuthorized($rootScope.userRole,toState.data.access);
if(!hasAccess){
event.preventDefault();
//user doesnt have access, show error and dont take him anywhere
}
}
});
});
3)在我的服务中(isAuthorized):
(function(){
'use strict';
angular.module('myApp')
.service('isAuthorized', function() {
return function(role,access){
//logic here that will see if data.access is present in the user roles, if yes it will return true else return false
return flag;
}
});
})();