Pierre Taquet
Pierre Taquet

Reputation: 101

basic HttpInterceptor never reached

I want to implement an HttpInterceptor in order to handle a 404 error. For now I just want to log something in the console when the HttpInterceptor is reached.

I implement a basic doNothing HttpInterceptor but nothing work.

app.module.ts

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { ErrorHandlerInterceptor } from './blocks/interceptor/errorhandler.interceptor';
@NgModule({
  imports: [
    ...
    HttpClientModule
  declarations: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ErrorHandlerInterceptor,
      multi: true
    }
  ],
  bootstrap: [MainComponent]
})

errorhandler.interceptor.ts

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('Hello');
    return next.handle(request);
  }
}

If you want to see the full code you can check my github

If I understood correctly, the console should display 'Hello' each time the interceptor is reached. But when I try to reached a non-existent url the console do not display 'Hello', just the error I want to handle...

Thanks for your help

Upvotes: 2

Views: 135

Answers (1)

Dzhavat Ushev
Dzhavat Ushev

Reputation: 735

The interceptor is used to handle outgoing requests. Let's say you use the HttpClient to make a get request. Then it will go through the interceptor. Trying to navigate to a non-existing route is not catched by the interceptor.

Upvotes: 1

Related Questions