Angular HTTP Interceptor how to chain an observable

强颜欢笑 提交于 2019-12-01 08:49:10

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

When you need to return something from Observable, you can use map instead of subscribe:

return this.authAzureService.getAccessToken()
  .map(token => request = this.getRequestWithHeaders(request, token));
}
request = request.clone({
  setHeaders: {
    Authorization: `Bearer ${token}`
  }
});
return next.handle(request);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!