Angular ui router - Redirection doesn't work at all

你离开我真会死。 提交于 2019-11-27 09:17:41
Radim Köhler

What we would need here, is to do NOT redirect, if the state TO is already the 'login'.

Just a drafted adjustment would be

$rootScope.$on( '$stateChangeStart', function(e, toState  , toParams
                                               , fromState, fromParams) {

    var isLogin = toState.name === "login";

    if(isLogin){

       return; // no need to redirect anymore 
    }
    ...

And also, we should call $state.go('login'); with the event.preventDefault();

 ...
 // also prevent default on redirect
 $state.go('login');
 event.preventDefault(); 
 ...

Please check this Q & A How can I fix 'Maximum call stack size exceeded' AngularJS And a plunker with similiar solution

I used something similar to this:

MyApp.run(['$rootScope', '$state', function ($rootScope, $state) {
  // The event
  $rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
    // Is user already logged in?
    var isUserLoggedIn = $rootScope.isUserLoggedIn();

    if (isUserLoggedIn) {
      // don't let user visit login state, he's already logged in.
      $state.go('home');
      // preventDefault as described in @radim's answer
      e.preventDefault();
    } else if (toState.name === "login") {
      // user is not logged in and is not going to login state right now, send him there first.
      $state.go('login');
      // preventDefault as described in @radim's answer
      e.preventDefault();
    }
  });
}]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!