我有一个有角度的应用程序,我创建了一个用于获取用户和授权的提供程序。在我的app.config中,我使用ui-router设置路由。对于第一个路由,我使用resolve属性来确保只有在用户具有admin角色时才会加载它。对于第二条路线,我想做同样的事情,除非它需要客户角色。我想使用与检查管理员角色完全相同的代码,但只需替换role='customer'
。有没有办法在不重复requireAdminRole
代码的情况下执行此操作?我试图找出一种方法将所需的角色从ui-router resolve
定义传递给提供者作为参数,但我无法弄清楚。
我的提供商定义:
angular.module('users').provider('Authentication', ['$windowProvider', function($windowProvider) {
var _this = this;
var $window = $windowProvider.$get();
_this.data = {user: $window.user};
this.$get = function () {
return _this.data;
};
this.requireAdminRole = ['$q', '$state', '$timeout', function ($q, $state) {
var role = 'admin';
var deferred = $q.defer();
if (_this.data.user.roles.indexOf(role) < 0) {
$timeout(function() {
deferred.reject();
$state.go('root');
}, 100);
} else {
deferred.resolve(_this.data.user);
}
return deferred.promise;
}];
}]);
我的路线:
angular.module('customer').config(['$stateProvider', 'AuthenticationProvider',
function($stateProvider, AuthenticationProvider){
$stateProvider.
state('listCustomers', {
url: 'admin/customers',
views: {
'content@': {
templateUrl: 'modules/customer/views/admin/list-customers.client.view.html',
controller: 'CustomerAdminController as customerCtrl'
}
},
resolve: {
CurrentUser: AuthenticationProvider.requireAdminRole
}
}).
state('survey', {
url: 'customers/survey',
views: {
'content@': {
templateUrl: 'modules/customer/views/view-customer.client.view.html',
controller: 'CustomerAdminController as customerCtrl'
}
},
resolve: {
CurrentUser: // This is where I want to reuse code from requireAdminRole
}
});