In order to bypass all interceptors we can use HttpBackend as @deg suggested.
In other cases we can create HttpClient factory that will allows us to exclude interceptors from the interceptors chain:
import { createHttpClient } from './http-client.factory';
// ...
@Injectable({
providedIn: 'root'
})
export class TodosApiService {
http = createHttpClient(this.injector, [Interceptor2]);
// ^^^^^^^^^^^^
// Interceptors to exclude
constructor(private injector: Injector) { }
getTodo() {
// Interceptor2 will be bypassed
return this.http.get('https://jsonplaceholder.typicode.com/todos')
}
}
Ng-run Example
Note that you can reuse this logic by creating base class:
@Injectable()
export class BasicHttpClient {
protected http = createHttpClient(this.injector, [Interceptor2]);
constructor(private injector: Injector) { }
}
@Injectable({ providedIn: 'root' })
export class TodosApiService extends BaseHttpClient {
getTodo() {
// Interceptor2 will be bypassed
return this.http.get('https://jsonplaceholder.typicode.com/todos')
}
}
http-client.factory.ts
import {
HTTP_INTERCEPTORS,
HttpBackend,
HttpClient,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injector, Type } from '@angular/core';
class HttpInterceptorHandler implements HttpHandler {
constructor(private next: HttpHandler, private interceptor: HttpInterceptor) {}
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
return this.interceptor.intercept(req, this.next);
}
}
class HttpInterceptingHandler implements HttpHandler {
private chain: HttpHandler | null = null;
constructor(
private backend: HttpBackend,
private injector: Injector,
private interceptorsToExclude: Type<HttpInterceptor>[],
private intercept?: (req: HttpRequest<any>) => HttpRequest<any>
) {}
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
if (this.intercept) {
req = this.intercept(req);
}
if (this.chain === null) {
const interceptors = this.injector
.get(HTTP_INTERCEPTORS, [])
.filter(
interceptor => !this.interceptorsToExclude.some(interceptorType => interceptor instanceof interceptorType)
);
this.chain = interceptors.reduceRight(
(next, interceptor) => new HttpInterceptorHandler(next, interceptor),
this.backend
);
}
return this.chain.handle(req);
}
}
export function createHttpClient(
injector: Injector,
excludedInterceptors: Type<HttpInterceptor>[],
intercept?: (req: HttpRequest<any>) => HttpRequest<any>
) {
return new HttpClient(
new HttpInterceptingHandler(injector.get(HttpBackend), injector, excludedInterceptors, intercept)
);
}