Angularjs ui-router. How to redirect to login page
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:
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.
Beware that actually $stateChangeSuccess
event is deprecated and no longer available in angular-ui-route
package. Now, this behavior is handled by transition hooks
. You could achieve your purpose using $transitions.onStart
as follows:
run.$inject = ['$transitions', 'authenticationSvc'];function run($transitions, authenticationSvc) { $transitions.onStart({}, function (trans) { var userInfo = authenticationSvc.getUserInfo(); var $state = trans.router.stateService; if(userInfo.authenticated === false) { $state.go('login'); // go to login } });}