【问题标题】:How to return the promise then()/catch() result to the function containing the promise?如何将 promise then()/catch() 结果返回给包含 promise 的函数?
【发布时间】:2017-10-18 14:23:31
【问题描述】:

在我的情况下,我正在使用 auth guard CanActivate() 限制每个路由的用户访问,但是条件值取自 http 请求 Promise 对象。如何访问 Promise then() 和 catch() 并将其返回给CanActivate(): Boolean 函数?

我的代码看起来像这样。

// On AuthService
verfifyUser(): Promise<any> {
    return this.http
      .get(`api/auth/verify-user`, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as any);
}


// On AuthGuardService
CanActivate(): Boolean {
    this.authSrv.verfifyUser(some_user).then(result => {
         // return true
    }).catch(err => {
         // return false 
    });
}

我仍然不知道如何解决这个问题。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    CanActivate接口的canActivate方法的返回类型为Observable&lt;boolean&gt;|Promise&lt;boolean&gt;|boolean

    您可以使用canActivate(): Promise&lt;boolean&gt; 版本并返回一个Promise。在函数中你可以写

    canActivate() : Promise<boolean> {
    
       return new Promise( resolve => {
    
          this.authSrv.verfifyUser(some_user).then(result => {
             resolve(true);
          }).catch(err => {
             resolve(false);
          });
    
       });
    
    }
    

    【讨论】:

    • 您好,我会尝试这个,但只是对结果感到好奇,在 ` { path: 'some-path/', component: ClientComponent, canActivate: [AuthGuard] } 上使用它仍然有效`?
    • @ShiftN'Tab 是的,当然,它是canActivate 函数的一种变体
    猜你喜欢
    • 2020-06-13
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    相关资源
    最近更新 更多