Angular 拦截器 return 值在 observable 之外

Angular interceptor return value outside observable

我正在使用 Angular 6,我正在编写一个 API,它使用访问令牌作为身份验证机制。基本上我使用拦截器在 headers 上设置授权承载令牌,然后将其作为请求发送。

起初我将访问令牌存储在本地存储中并从那里获取它以将其设置为授权持有者。但是,我现在正在使用 IndexDB,因为我将开始使用服务工作者和 PWA。所以我现在正在使用一个异步库 @ngx-pwa/local-storage,它将所有内容都包装在可观察对象中。

现在我不知道如何return函数外的值,因为我需要在发送下一个拦截句柄之前以同步方式获取令牌。这样做的最佳方法是什么?

this.localStorage.getItem('access_token').subscribe(token => {
  const cloned = req.clone({
    headers: req.headers.set('Authorization', 'Bearer ' + token)
  });
  return next.handle(cloned); // does not work
});

您可以尝试使用 async/await 关键字:

async someFunction(...){
    ....
    const token = await this.localStorage.getItem('access_token').toPromise();
    const cloned = req.clone({
        headers: req.headers.set('Authorization', 'Bearer ' + this._auth.ACCESS_TOKEN)
    });
    // Do whatever you need to with 'cloned'
}

await 关键字将强制执行函数,直到 localStorage.getItem 调用完成。

所以 this.localStorage.getItem('access_token') 从 IndexDB 获取键,returns 从 Observable 获取。您唯一需要做的就是等到 getItem 完成,然后继续 next.handle(cloned),这意味着您可以使用例如 concatMap 运算符:

return this.localStorage.getItem('access_token')
  .pipe(
    concatMap(token => {
      const cloned = req.clone({
        headers: req.headers.set('Authorization', 'Bearer ' + token)
      });
      return next.handle(cloned);
    })
  );

以上代码将转到您的拦截器。