Indhu
Indhu

Reputation: 399

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?

Upvotes: 3

Views: 5948

Answers (2)

Murage
Murage

Reputation: 656

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

Upvotes: 4

Rahul
Rahul

Reputation: 2128

Http interceptor is just a service there won't be any difference in injecting it on any modules - just do the same in AppModule that will help you to work - if in case you have the same problem you can try injecting like below on your shared module

The common pattern to achieve that is not to expose providers directly on the @NgModule declaration but in a static forRoot function like that:

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
         { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }
      ]
    };
  }
}

You can then import your SharedModule on AppModule like SharedModule.forRoot()

Hope this works - Happy coding

Upvotes: 2

Related Questions