Angular HTTP Interceptor如何链接一个observable

时间:2018-03-22 19:48:44

标签: angular rxjs rxjs5 adal adal.js

我正在使用Azure AD adal库进行身份验证。有一个调用获取一个返回一个observable的令牌。如何将这种可观察性添加到拦截中?在下面的示例中,如何将订阅中设置的请求作为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);
  }

3 个答案:

答案 0 :(得分:2)

感谢@Commecial Suicide,我找到了解决方案,即使用flatMap。以下是有效的代码:

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

答案 1 :(得分:1)

如果您需要从Observable返回某些内容,则可以使用map代替subscribe

return this.authAzureService.getAccessToken()
  .map(token => request = this.getRequestWithHeaders(request, token));
}

答案 2 :(得分:0)

request = request.clone({
  setHeaders: {
    Authorization: `Bearer ${token}`
  }
});
return next.handle(request);