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
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 theonRetain
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With