Angular HTTP Interceptor how to chain an observable

后端 未结 3 1500
栀梦
栀梦 2021-01-14 15:43

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?

相关标签:
3条回答
  • 2021-01-14 15:50

    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));
    }
    
    0 讨论(0)
  • 2021-01-14 16:12
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`
      }
    });
    return next.handle(request);
    
    0 讨论(0)
  • 2021-01-14 16:15

    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;
      }
    
    0 讨论(0)
提交回复
热议问题