Ui-Router $state.go inside $on('$stateChangeStart') is cauzing an infinite loop

前端 未结 6 1808
南方客
南方客 2020-12-03 10:52

I\'m trying to introduce login into the way the user navigates accross the application.

I pretend to redirect the user to the page were he was before he navigate to

6条回答
  •  一生所求
    2020-12-03 11:25

    In general I would say, let's redirect ($state.go()) only if needed. In other cases, get out from the event listener:

    if (toState.name === 'login' ){
      // doe she/he try to go to login? - let him/her go
      return;
    }
    
    if(Auth.isLoggedIn()){
       // is logged in? - can go anyhwere
       return;
    }
    
    // else
    $state.go('login')
    

    This is simplified logic, but shows, that we should change to execution only if needed. There are some other examles with more detailed implementation and plunkers:

    • Confusing $locationChangeSuccess and $stateChangeStart
    • Angular UI Router: nested states for home to differentiate logged in and logged out
    • other example of log in
    • angular ui-router login authentication

    As provided in the comment, there was plunker, which I changed like this here

    ...
    // three new lines
    if (toState.name === 'specialRoute'){
      return;
    }
    
    if (fromState.name=='route1'){
      event.preventDefault();
      $state.go('specialRoute')
    }
    

    And this is not looping anymore. Please, check it here

提交回复
热议问题