How use async service into angular httpClient interceptor How use async service into angular httpClient interceptor angular angular

How use async service into angular httpClient interceptor


If you need to invoke an async function within interceptor then the following approach can be followed using the rxjs from operator.

import { MyAuth} from './myauth'import { from } from 'rxjs'@Injectable()export class AuthInterceptor implements HttpInterceptor {  constructor(private auth: MyAuth) {}  intercept(req: HttpRequest<any>, next: HttpHandler) {    // convert promise to observable using 'from' operator    return from(this.handle(req, next))  }  async handle(req: HttpRequest<any>, next: HttpHandler) {    // if your getAuthToken() function declared as "async getAuthToken() {}"    await this.auth.getAuthToken()    // if your getAuthToken() function declared to return an observable then you can use    // await this.auth.getAuthToken().toPromise()    const authReq = req.clone({      setHeaders: {        Authorization: authToken      }    })    // Important: Note the .toPromise()    return next.handle(authReq).toPromise()  }}


I think that there is a issue about the reactive flow. The method intercept expects to return an Observable and you have to flatten your async result with the Observable returned by next.handle

Try this

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {      return this.asyncService.applyLogic(req).mergeMap((modifiedReq)=> {        const newReq = req.clone(modifiedReq);        return next.handle(newReq);    });}

You could also use switchMap instead of mergeMap


Asynchronous operation in HttpInterceptor with Angular 6.0 and RxJS 6.0

auth.interceptor.ts

import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http';import { Injectable } from '@angular/core';import { Observable } from 'rxjs/index';;import { switchMap } from 'rxjs/internal/operators';@Injectable()export class AuthInterceptor implements HttpInterceptor {  constructor(private auth: AuthService) {}  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {    return this.auth.client().pipe(switchMap(() => {        return next.handle(request);    }));  }}

auth.service.ts

import { Injectable } from '@angular/core';import { Observable } from 'rxjs';@Injectable()export class AuthService {  constructor() {}  client(): Observable<string> {    return new Observable((observer) => {      setTimeout(() => {        observer.next('result');      }, 5000);    });  }}