Search code examples
angularrxjsobservabletoken

Await promise in an rxjs obervable pipe


When the access token expires, the backend return 401. I need to fetch a new token and then resend the failed request.

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  req = req.clone({
    setHeaders: {
      'Authorization': 'Bearer s' + this.authService.authToken
    }
  });
   return next.handle(req);

I tried to use pipe as follows:

 return next.handle(req).pipe(
      catchError( async (err) => {
        if(err.status == 401){
          // Regenrate token. regenerateToken function is a promise
          await this.authenticationService.regenerateToken()
          //resend request
          return next.handle(req);
        }
      })
    );

but the issue is the catchError should return an observable of HttpEvent, and since the function that generates a new token is a promise, the async catchError function doesn't return an observable of HttpEven.

How can I generate a new token on 401, then resend the failed request when my generating token function is an async function?


Solution

  • You can turn the Promise into an Observable (using from() function) and then chain it with the next request:

    catchError( async (err) => {
      if (err.status == 401){
        // Regenrate token. regenerateToken function is a promise
        return from(this.authenticationService.regenerateToken())
          .pipe(
            mergeMap(() => next.handle(req))
          )
      }
    })