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

Ember: wait for promise in router.willTransition hook

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

我使用 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')
    })
}

这只是一个真实的例子我更喜欢user.isCat并且允许猫进入/cats和/cute路线。

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

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

因此您的示例将如下所示:

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

参见:

willTransitionTo 不会停止承诺。所以最好的实现方式是在这种情况下中止转换。像下面这样的东西可以帮到你。

willTransition: function(transition) {
   return this.get('session').authenticate('authenticator:application').then(() => {
      if(!this.get('user.isAdmin')){
         transition.abort();
      }
      if(!this.get('user.isCat')){
         transition.abort();
      }
   });
}

希望对您有所帮助。