Home > Enterprise >  Angular 12/rxjs 7/angularfire: async token interceptor with deprecated toPromise
Angular 12/rxjs 7/angularfire: async token interceptor with deprecated toPromise

Time:09-24

I am using angularfire with and auth interceptor adding a token to every request. This interceptor requires an async call as the token might requires a refresh.

With an update to rxjs 7, my async tokenHandler now faces two issues:

  • the .toPromise() is depcrated
  • the async tokenHandler may returns undefined (Type 'HttpEvent | undefined' is not assignable to type 'HttpEvent')
@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const fireUser = this.auth.fireAuthUser.value;

    if (fireUser) {
      // convert promise to observable using 'from' operator
      return from(this.tokenHandler(request, next, fireUser));
    }

    return next.handle(request);
  }

  async tokenHandler(request: HttpRequest<any>, next: HttpHandler, currentUser: firebase.User): Promise<HttpEvent<any>> {
    const authToken = await currentUser.getIdToken().then();

    if (authToken) {
      request = request.clone({ setHeaders: { Authorization: 'Bearer '   authToken } });
    }

    return next.handle(request).toPromise();
  }
}

Could you advise me on how to rewrite the async tokenHandler?

CodePudding user response:

stream$.toPromise() is most semantically similar to the new lastValueFrom(stream$) except:

The type information of toPromise was wrong.

When the source Observable completed without ever emitting a single value - it resolved with undefined. It should reject in that case, but it doesn't. lastValueFrom and firstValueFrom will both reject in this case.

Therefore, you can fix this with lastValueFrom or firstValueFrom.

async tokenHandler(
  request: HttpRequest<any>, 
  next: HttpHandler, 
  currentUser: firebase.User
): Promise<HttpEvent<any>> {
  const authToken = await currentUser.getIdToken();

  if (authToken) {
    request = request.clone({ setHeaders: { Authorization: 'Bearer '   authToken } });
  }

  return lastValueFrom(next.handle(request));
}
  • Related