I get an infinite digest loop inside my $stateChangeStart handler when the app initially loads.
I have already reviewed the current postings on this. While my problem seems to be exactly as these posts state, none of the solutions and answers proposed nor the accepted answers solve my particular issue. I am not trying to solve the authorization topic, I am trying to resolve permission to go to route based on the user's role.
- Infinite Loop on ui-router's $stateChangeStart
- Ui-Router $state.go inside $on('$stateChangeStart') is cauzing an infinite loop
- Divert to alternate homepage if user is not logged in using UI-Router & AngularJS
I added the following object to the $state object when a route is defined
$stateProvider.state('routeName', {
// ...
authorization: {
allowAll: false,
allowRoles: [
'admin',
'power',
'user',
'guest'
],
denyAll: false,
denyRoles: [{
role: 'user',
route: 'dashboard',
data: {
//...
}
},{
role: 'power',
route: 'dashboard',
data: {
//...
}
}],
failover: "home"
}
});
I have this as my handler for $stateChangeStart
$rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
var userRole = UserFactory.role;
// default to app route if route 'failover' not defined
var failOver = toState.authorization.failover || 'home';
// User is allowed to continue through to the state.
if (toState.authorization.allowAll ||
_.contains(toState.authorization.allowRoles, userRole)) {
// Do nothing user is allowed this route
return;
} else if (!toState.authorization.denyAll &&
toState.authorization.denyRoles.length > 0) {
// User is denied this route find the route to redirect to
var entry = _.find(toState.authorization.denyRoles, function (item) {
return item.role == userRole;
});
if (entry) {
e.preventDefault();
$state.go(entry.route, entry.data || { });
return;
}
}
// All deny conditions not specifically targeted
e.preventDefault();
$state.go(failOver);
});
Here is the full plunker.