3

I have created HTTP_INTERCEPTOR, I need it to work on some specific routes and some others not.

At the begining it was in the main app module file, then I removed it from there and add it in some modules,but it still work on all routes , then i added it in component.ts but not worked at all.

{
            provide: HTTP_INTERCEPTORS,
            useClass: AuthExpiredInterceptor,
            multi: true,
            deps: [Injector]
},
Mikhail Fayez
  • 421
  • 3
  • 15

1 Answers1

14

It's not possible to only specify an interceptor for certain routes and/or modules.

However, you can add a http header value that skips applying the interceptor for that request. For Example:

import { HttpHeaders } from '@angular/common/http';
export const InterceptorSkip = 'X-Skip-Interceptor';
export const InterceptorSkipHeader = new HttpHeaders({
  'X-Skip-Interceptor': ''
});

then in my Error handler Interceptor if the header is applied, do not catch the error and handle it, instead, let it bubble up to my services and components.

@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>,next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (request.headers && request.headers.has(InterceptorSkip)) {
      const headers = request.headers.delete(InterceptorSkip);
      return next.handle(request.clone({ headers }));
    }
    return next.handle(request).pipe(catchError(this.processError));
  }


  ...

}

then anytime you have a HTTP request you want to be ignored add the InterceptorSkipHeader to the request

this.http.get<ResponseModel>('api/url', { headers : InterceptorSkipHeader });
JoshSommer
  • 2,550
  • 18
  • 23