3
votes

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?

2
Its not required to HttpClientModule in AppModule however you need to immediate Module which uses Http. Better to put into SharedModule instead. - Sunil Singh
@SunilSinghit gives error if I don't use HttpClientModule in AppModule - Pritam Bohra
It means you did not add HttpClientModule in all Modules which is using Http. - Sunil Singh
@SunilSingh I did not add HttpClientModule to the AppModule as it was not making any Http requests and had added it only to the FeatureModule as it was the only module making Http requests. However, that was not working and I had to add HttpClientModule to the AppModule in order to get rid of the error. I am not sure where I went wrong. - Pritam Bohra
Please create stackblitz demo. - Sunil Singh

2 Answers

5
votes

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

0
votes

The last answer it's great, best practices say that you only need one HtppclientModule and it's better if you put this into core.module.ts and import core.module.ts into app.module.ts.

core.module.ts

enter image description here

app.module.ts

enter image description here