Angular HTTP拦截器如何链接可观察的 [英] Angular HTTP Interceptor how to chain an observable

查看:94
本文介绍了Angular HTTP拦截器如何链接可观察的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Azure AD adal库进行身份验证。有一个调用来获取返回可观察值的令牌。如何将此可观察值添加到截距中?在下面的示例中,如何获取在订阅中设置的请求以Observable的形式返回?

I am using the Azure AD adal library to do authentication. There is a call to aquire a token that returns an observable. How can this observable be added into the intercept? In the below example, how can I get the request that is set inside the subscribe to be returned as the Observable?

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.authAzureService.getAccessToken()
    .subscribe(token => {
      // I need this to be returned
      request = this.getRequestWithHeaders(request, token);
    });

    // This returns the request before the access token is added
    return next.handle(request);
  }


推荐答案

感谢@Commercial Suicide I找到了解决方案,那就是使用flatMap。这是有效的代码:

Thanks to @Commecial Suicide I found the solution, which is to use a flatMap. Here is the code that worked:

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let requestHandler = this.authAzureService.getAccessToken()
    .flatMap(token => {
      request = this.getRequestWithHeaders(request, token);
      return next.handle(request);
    });
    return requestHandler;
  }

这篇关于Angular HTTP拦截器如何链接可观察的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆