- Solution 1
The easiest solution is to create plain HttpClient using HttpBackend.
This will completely bypass all interceptors:
function initializeAppFactory(httpBackend: HttpBackend): () => Observable<any> {
const httpClient = new HttpClient(httpBackend);
return () => httpClient.get("http://localhost/api/v1/user")
.pipe(
tap(user => {
// do something with user
})
);
}
@NgModule({
imports: [BrowserModule, HttpClientModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializeAppFactory,
deps: [HttpBackend],
multi: true
}]
})
export class AppModule {
}
- Solution 2
Sometimes you still want to use interceptors, but just want to disable some parts of them. To do this we can pass custom header to the request and use it in the interceptors we want to bypass.
Let’s assume we have Interceptor called “SkippableInterceptor”, by checking headers for InterceptorSkipHeader we can know if the interceptor should be skipped:
export const InterceptorSkipHeader = 'X-Skip-Interceptor';
@Injectable()
export class SkippableInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.headers.has(InterceptorSkipHeader)) {
const headers = req.headers.delete(InterceptorSkipHeader);
return next.handle(req.clone({ headers }));
}
// ...intercept
}
}
Then whenever you want to bypass the interceptor, simply add InterceptorSkipHeader to the request headers:
const headers = new HttpHeaders().set(InterceptorSkipHeader, '');
this.httpClient
.get<ResponseType>(someUrl, { headers })
This was very helpful, thank you!
You’re welcome 🙂