Angular ui router - Redirection doesn't work at all

前端 未结 2 970
生来不讨喜
生来不讨喜 2020-12-01 22:19

I\'m using ui.router for routing in my Angular app. There is a typical login scenario, where I\'m redirecting a user to the login url if he\'s not logged in. Wi

2条回答
  •  借酒劲吻你
    2020-12-01 22:41

    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

提交回复
热议问题