Ember:在 router.willTransition 钩子中等待承诺

Ben*_*lex 2 javascript promise ember.js

我想允许一些用户输入路线,而其他用户则不允许。

我使用simple auth进行身份验证,它会使用承诺加载用户数据。问题是willTransition()不会等到我的用户被加载,所以它会显示索引路由,然后我才能检查用户是否有权访问它。

所以在 router.js 我有:

willTransition(oldRoute, nextRoute, transition) {
    return this.get('session').authenticate('authenticator:application').then(() => {
      if(this.get('user.isAdmin')) return true
      else alert('not allowed to enter')
    })
}
Run Code Online (Sandbox Code Playgroud)

这只是一个真实的例子,我有更多的喜欢user.isCat和 cat 被允许进入 /cats 和 /cute 路线。

我知道,我可以检查user.isAdmin也beforeModel()路线,但我有很多其他的路线和权限组,所以我想在路由器一个地方来管理。

Jos*_*osa 5

您可以中止转换并在承诺解决后重试。

所以你的例子看起来像这样:

willTransition(transition) {
  if (this.get('pendingTransition.targetName') == transition.targetName) {
    this.set('pendingTransition', null);
    return true;
  }

  transition.abort();

  this.get('session').authenticate('authenticator:application').then(() => {
    if (this.get('user.isAdmin')) {
      this.set('pendingTransition', transition);
      transition.retry();

    } else {
      alert('not allowed to enter')
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

看: