Angularjs ui-router. How to redirect to login page

老子叫甜甜 提交于 2019-11-27 02:58:05
Radim Köhler

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
    }
  });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!