Search code examples
angularangular-http-interceptors

HTTP_INTERCEPTORS only in AppModule


I am trying to implement lazy loading in my Angular 6 app, all of my http calls are made in the FeatureModule (lazy loaded), but still I have to add HttpClientModule in my AppModule and not in FeatureModule. Didn't really understand why. Also, when I added interceptors in my FeatureModule, they didn't intercept any request. I have to add it in the AppModule only (I guess, it is because HttpClientModule is in AppModule).

I want to understand why this is the case?? Why can't we have HttpClientModule and HTTP_INTERCEPTORS only in the FeatureModule and not in AppModule where I am not making any http calls?


Solution

  • To answer this question.

    Only add HttpClientModule at once place at the root level. No other modules regardless of how they are imported lazy or eager even if it is from a library. Ensure that it is not importing HttpClientModule

    You can however use HTTP_INTERCEPTORS providers across modules without an issue.

    When you import HttpClientModule across modules and then re import that into another module it effectively resets the providers for HTTP_INTERCEPTORS for that module. This is an intended behaviour. If you need more information about the discussion you can check: https://github.com/angular/angular/issues/20575