Ember:在router.willTransition钩子中等待promise

时间:2017-08-07 13:01:51

标签: javascript ember.js promise

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

我使用simple auth进行身份验证,它将使用promise加载用户数据。问题是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')
    })
}

这只是一个真实的例子,我更像user.isCat,猫可以进入/猫和/可爱的路线。

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

1 个答案:

答案 0 :(得分:3)

您可以中止过渡并在承诺解决后重试。

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

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')
    }
  })
}

请参阅: