Angularjs ui-router. How to redirect to login page
Solution 1:
The point is, do not redirect if not needed === if already redirected to intended state. There is a working plunker with similar solution
.run(function($rootScope, $location, $state, authenticationSvc) {
$rootScope.$on( '$stateChangeStart', function(e, toState , toParams
, fromState, fromParams) {
var isLogin = toState.name === "login";
if(isLogin){
return; // no need to redirect
}
// now, redirect only not authenticated
var userInfo = authenticationSvc.getUserInfo();
if(userInfo.authenticated === false) {
e.preventDefault(); // stop current execution
$state.go('login'); // go to login
}
});
});
Check these for similar explanation:
- Angular ui router - Redirection doesn't work at all
- How can I fix 'Maximum call stack size exceeded' AngularJS
Solution 2:
Since you are using UI-Router module, you should be using $stateChangeStart
, $stateChangeSuccess
events.
Check this link for more: https://github.com/angular-ui/ui-router/issues/17
Also there is a typo in consol.log(userInfo)
in console.
Check the console in your chrome-dev-tools. It will give idea if something else is missing.