1

error:

enter image description here

Yes i know there have been posts similar to this one but they do not address my issue. I want to take full control of the app's routing.My code is as follows:

a few things to note would be that i have attached a custom property to my states called authenticate which has a true or false value. I have also created a simple function, get user. All it does is retrieve the user from the api.

$rootScope.$on('$stateChangeStart', function(event, toState) {
  event.preventDefault();
  let token = $cookies.get('token');

  if (toState.authenticate) {
    if (token) {
      getUser()
        .then(user => {
          $rootScope.user = user;
          $state.go(toState.name);
        })
        .catch(err => console.log(err));
    } else {
        $state.go('login');
    }
  } else {
      $state.go(toState.name);
  }
});

I first check if the state requires authentication. If it does not we simply continue to the state. If it does require authentication we check if there is a token. if there is we fetch the user using the function I mentioned earlier. If there isn't a token we send the user to the login state.

  • 1
    why do you need event.preventDefault(); there? – Thalaivar Jun 02 '16 at 20:55
  • Because otherwise the app tries to go to the state without me being able to check if authentication is needed. – Maximilian Lloyd Jun 02 '16 at 20:57
  • on what condition the event.preventDefault(); is called, its going infinite and its what the error is being thrown... – Thalaivar Jun 02 '16 at 20:58
  • What do you mean, there is not a condition. I call it once the event handler fires. – Maximilian Lloyd Jun 02 '16 at 21:00
  • 1
    You are calling event.preventDefault() every time there is a change in state... $rootScope.$on('$stateChangeStart', function(event, toState) { – Thalaivar Jun 02 '16 at 21:22
  • There is a detailed explanation and working plunker http://stackoverflow.com/q/25872219/1679310 – Radim Köhler Jun 03 '16 at 06:08
  • 1
    though I am aware @RadimKöhler's solution works well and so are the explanations well put, I highly recommend to use the `resolve` function in `ui-router`. It's cleaner and more elegant, and no global variables, yeay. – CozyAzure Jun 03 '16 at 06:11
  • @CozyAzure this is a nice point. In case, that application (or state hierarchy) can be blocked - resolve is a standard - synchronous solution. In case, we want dispatch user with some features regardless security (anonymous) ... resolve will break it, because it is really blocking.. until resolved. But nice point – Radim Köhler Jun 03 '16 at 06:16

0 Answers0