How to add HttpClient Interceptors conditionally in Angular

I recently used Interceptors with Angular HttpClient.

I am adding headers corresponding to some HTTP GET methods, and for some I do not need these headers.

How can I say that my interceptor conditionally adds interceptors only to these methods? I can even separate services as one service for headers, and one without headers or one for different headers, and another for different.

NgModule Suppliers

{
  provide: HTTP_INTERCEPTORS,
  useClass: AuthInterceptor,
  multi: true,
},{
  provide: HTTP_INTERCEPTORS,
  useClass: AngularInterceptor,
  multi: true,
}

Myinterceptors

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({headers: req.headers.set('X-Auth-Token', "-------------------------")});
    return next.handle(authReq);

  }
}


@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {}, err => {
        if(err instanceof HttpErrorResponse){
            console.log("Error Caught By Interceptor");
            //Observable.throw(err);
        }
    });
  }
}
+4
source share
1 answer

Note. I have not tried this approach yet, but have been playing with the idea because we are looking at a similar problem.

, URL/, . , angular API . .

HttpClient API/, . , angular HttpClient :

 providers: [
    HttpClient,
    // HttpHandler is the backend + interceptors and is constructed
    // using the interceptingHandler factory function.
    {
      provide: HttpHandler,
      useFactory: interceptingHandler,
      deps: [HttpBackend, [new Optional(), new Inject(HTTP_INTERCEPTORS)]],
    },

interceptingHandler ɵinterceptingHandler. , , , .

Anyawy, HttpClients :

export const MY_HTTP_INTERCEPTORS = new InjectionToken<HttpInterceptor[]>('MY_HTTP_INTERCEPTORS');

...
 providers: [
    MyHttpClient,
    {
      provide: MyHttpHandler,
      useFactory: interceptingHandler,
      deps: [HttpBackend, [new Optional(), new Inject(MY_HTTP_INTERCEPTORS)]],
    },

, MyHttpClient MyHttpHandler .

+1

Source: https://habr.com/ru/post/1684061/


All Articles