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

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:

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

Leave a Comment