Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ui-router: Difference between onEnter and onStart?

I'm switching to new version of ui-router (1.0.0-alpha.5) and trying to figure out where to use onEnter hook and where onStart:

$transitions.onStart()

and

$transitions.onEnter()

before it was just event $stateChangeStart

like image 911
Stepan Suvorov Avatar asked Mar 12 '23 15:03

Stepan Suvorov


1 Answers

Here's how the doc describes the transition lifecycle hooks execution order:

onBefore
onStart/onInvalid
onEnter (for individual states)
onSuccess
onError

... but it seems to be a little bit outdated (I'll get back to that later). Still, it clearly shows that onEnter hooks are about entering a state, and onStart hooks are about starting a Transition between states.

Actually, that key difference is described quite well in the hook doc pages:

onStart hooks are invoked asynchronously, in priority order, when the Transition starts running. At this point, the Transition has not exited nor entered any states yet.

onEnter hooks are invoked asynchronously, in priority order, when the Transition is entering a state. States are entered after the onRetain hooks.

onStart hook seems to be a good place to validate a transition - for example, to check whether or not a user is authenticated. Here's a code example given in that doc:

$transitions.onStart( { to: 'auth.*' }, function(MyAuthService, $state) {
  // If the user is not authenticated
  if (!MyAuthService.isAuthenticated()) {

    // Then return a promise for a successful login.
    // The transition will wait for this promise to settle
    return MyAuthService.authenticate().catch(function() {

      // Redirect to a state that we know doesn't require auth.
      return $state.target("guest");
    });
  }
});

Judging from that last page, the order actually is:

onBefore - Transition is about to start; one can register other hooks here "on-the-fly"
onStart  - Transition starts running
onExit   - Transition is exiting a state
onRetain - Transition retains a state
onEnter  - Transition is entering a state 
onFinish - Transition is about to be completed, all states are entered and exited

onSuccess/onError - Transition is completed (either successfully or not)

NB: all but the last two hooks can modify the transition - change the target state etc. onSuccess and onError are fired post factum: the transition is over.

like image 69
raina77ow Avatar answered Mar 16 '23 00:03

raina77ow