在文檔中沒有提到這樣的事情,但這裏是我如何實現它。
基本上,我在我的$ 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運行函數I訪問這些當狀態改變事件發生時:
此外,我使用服務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;
}
});
})();
檢查我的答案是否有幫助 –