我正在使用Angular UI-Router在我的前端应用程序中实现状态。我的抽象基础状态上有一个resolve
组,我从所有子状态延伸出来,但我遇到了问题:
我看了这个Q / A: How do I access the 'resolve' property of a UI-Router root state from $stateChangeStart? ......但它并没有真正回答我的问题。这是代码:
.state('app', {
abstract: true,
url: '/',
templateUrl: 'build/views/layout/master.html',
data: {
doesRequireLogin: true
},
resolve: {
principalRoles: function($q, User, RoleMapping, $rootScope) {
var deferred = $q.defer();
// Grab the current user, then attempt to find their roles
User.getCurrent(
function foundUser(user) {
RoleMapping.find({
filter: {
where: {
principalId: user.id
},
include: 'role'
}
}, function hasRoles(roleMappings) {
// Reduce the roles list to just the names of the roles
var rolesList = roleMappings.map(function(mapping) {
return mapping.role ? mapping.role.name : '';
});
$rootScope.user.roles = rolesList;
return deferred.resolve(rolesList);
}, function hasError(error) {
return deferred.reject(error);
});
},
function userError(error) {
return deferred.reject(error);
}
);
return deferred.promise;
}
}
})
这很好用,似乎返回了我需要的信息。不过我的问题是在我的.run
块中,我有以下代码:
// Intercept state changes to see if we need to log in
$rootScope.$on('$stateChangeStart', function (event, toState, toParams
, fromState, fromParams) {
console.log(arguments);
var requireLogin = toState.data.doesRequireLogin;
console.log(toState.data.principalRoles);
try {
// this only works because i assign this in the state,
// probably not the best idea,
// and besides it only works *after* the first page load, never initially
console.log($rootScope.user.roles);
}
catch(e) {}
if (requireLogin && !$rootScope.isAuthenticated) {
event.preventDefault();
$state.go('auth')
}
});
这仅适用于初始页面加载后的后续状态更改 ,您能想到如何为所有实例返回当前用户的角色吗?