4

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);
  }
Michael Witt
  • 1,582
  • 4
  • 22
  • 43

3 Answers3

4

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;
  }
Michael Witt
  • 1,582
  • 4
  • 22
  • 43
1

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));
}
P.S.
  • 15,970
  • 14
  • 62
  • 86
-1
request = request.clone({
  setHeaders: {
    Authorization: `Bearer ${token}`
  }
});
return next.handle(request);
erni
  • 176
  • 1
  • 1
  • 10