ui-router:onEnter和onStart之间的区别?

时间:2016-07-21 06:49:13

标签: javascript angularjs angular-ui-router

我正在切换到 ui-router 的新版本(1.0.0-alpha.5)并尝试找出使用 onEnter 挂钩的位置其中 onStart

$transitions.onStart()

$transitions.onEnter()

之前它只是事件 $ stateChangeStart

1 个答案:

答案 0 :(得分:7)

以下是the doc描述转换生命周期挂钩执行顺序的方法:

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

...但似乎有点过时(我稍后再回过头来看)。不过,它清楚地表明onEnter挂钩是关于进入状态,而onStart挂钩是关于开始状态之间的转换

实际上,在the hook doc pages中很好地描述了这一关键差异:

  

onStart挂钩以优先级顺序异步调用   转换开始运行。 此时,过渡没有   退出也没有进入任何州。

     

onEnter挂钩以优先级顺序异步调用   转型正在进入一个州。国家进入后   onRetain挂钩。

onStart挂钩似乎是验证转换的好地方 - 例如,检查用户是否经过身份验证。这是该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");
    });
  }
});

从最后一页判断,订单实际上是:

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)

注意:除了最后两个钩子之外的所有钩子都可以修改过渡 - 更改目标状态等。onSuccessonError在事后发生:过渡结束。