angulartypescriptroutes

Why isn't my HTTP interceptor working with Angular's new provideHttpClient strategy?


I'm working with Angular's new provideHttpClient strategy introduced in Angular 15+. I want to apply an HTTP interceptor for a specific route, but the interceptor doesn't seem to be triggered, and I can't see my console.log statement in the browser's console.

{
  path: 'test',
  providers: [
    provideHttpClient(
      withRequestsMadeViaParent(),
      withInterceptors([
        (req: HttpRequest<any>, next: HttpHandlerFn) => {
          console.log('Interceptor fired');
          return next(req).pipe(
            catchError((err: HttpErrorResponse) => {
              if (err.status === 403 || err.status === 404) {
                console.log('error')
              }
              return throwError(() => err);
            })
          );
        },
      ])
    ),
  ],
  children: [{},{}...]
}

Here are some things I've tried/considered:

I've double-checked the path navigation, and it matches. I wonder if there's something I'm missing with withRequestsMadeViaParent() or if I need to declare provideHttpClient elsewhere. Is there something I'm missing in the configuration for this interceptor to work as expected? Do I need to declare something globally or set up provideHttpClient in a specific way for the route?

Any help would be appreciated!


Solution

  • Hard so say without all seeing the components involved. But most likely your service which injects httpClient is provided in higher than this interceptor in the DI hierarchy tree. This is a nice piece of documentation you can read about DI hierarchy in angular - https://angular.dev/guide/di/hierarchical-dependency-injection.

    You can test it very easily. Take the service that uses httpClient, and provide it in your path's providers (in the same array when you provide the http inerceptor). If it works, the issue is what I described above.