Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import Angular HTTP interceptor only for Child module

I have imported HttpClientModule in AppModule.

import { HttpClientModule } from '@angular/common/http';

export const AppRoutes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  {
    path: 'account',
    loadChildren: './auth/auth.module#AuthModule'
  },
  {
    path: 'dashboard',
    loadChildren: './content/content.module#ContentModule'
  }
];

Once I launch site, it will redirect to dashboard module(Lazy loaded module) where i added http interceptor.

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpInterceptorService } from '../services/http-interceptor.service';
@NgModule({
providers : [
      { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }
    ]
})

But it doesn't working. Can anyone help me?

like image 820
Indhu Avatar asked Jul 17 '26 20:07

Indhu


1 Answers

This question is old but for the future stumblers on this thread and expanding on the accepted answer:

Angular interceptors should be registered before injecting the Http client

Because interceptors are (optional) dependencies of the HttpClient service, you must provide them in the same injector (or a parent of the injector) that provides HttpClient. Interceptors provided after DI creates the HttpClient are ignored.

Thus, one should provide any interceptors before HttpClientModule import which injects HttpClient service automatically(side effect)

Source: https://angular.io/guide/http#provide-the-interceptor

like image 108
Murage Avatar answered Jul 20 '26 09:07

Murage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!