首页 文章

角度拦截器返回值在可观察之外

提问于
浏览
0

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

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

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

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

2 回答

  • 1

    您可以尝试使用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 调用完成 .

  • 0

    所以 this.localStorage.getItem('access_token') 从IndexDB获取密钥并返回一个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);
        })
      );
    

    上面的代码将转到你的拦截器 .

相关问题