I'm using Angular UI-Router to achieve state within my frontend app. I've got a resolve
group on my abstract base state, which I extend from with all of my child states, but I'm experiencing issues:
I looked at this Q/A: How do I access the 'resolve' property of a UI-Router root state from $stateChangeStart? ... but it didn't really answer my question. Here's the code:
.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;
}
}
})
This works fine, seems to return the information I need. However my issue is that inside my .run
block, I have the following code:
// 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')
}
});
This only works on subsequent state changes after the initial page load, can you think of how I could return the current user's roles for all instances?