Solvedangular HTTP_INTERCEPTORS are reset when a lazy loaded module imports another module importing HttpClientModule

I'm submitting a...

[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

The HTTP_INTERCEPTORS provider token is reset when a lazy loaded module imports another module which imports the HttpClientModule by itself.

Expected behavior

The HTTP_INTERCEPTORS from the parent injector should be used.

Minimal reproduction of the problem with instructions

https://plnkr.co/edit/up8P57jwD3lUAZ9WyMS4

What is the motivation / use case for changing the behavior?

It seems that this is currently by design that a parent injector is not asked for the already registered providers from a multi-provider token. In my opinion it is not uncommon to have some kind of shared module which is also importing the HttpClientModule (because it want's to issue HTTP calls, but should not depend on having the module imported in the app module).

Is there any other way to implement this scenario?

Likely relates also to #18894 in some kind.

Environment

Angular version: 5.0.2
36 Answers

✔️Accepted Answer

Before you can use the HttpClient, you need to install the HttpClientModule which provides it. This can be done in your application module, and is only necessary once.

You should import the HttpClientModule only once, see docs

Other Answers:

@mhevery Ok, maybe just with some more info/explanation how this should be handled when its intended? Just saying intended behavior and closing isn’t quite satisfying for all having this issue.

Is the tenor to only import the HttpClientModule in the bootstrapping module and never anywhere else? It would be kind to confirm this at least. :)

Thanks for your help.

@mlc-mlapis The funny thing is that this breaks currently, I have the HttpClientModule in my app module (see the Plunker), but when a lazy loaded module imports a module that imports the HttpClientModule, too, the interceptors are gone. This is because that multi-providers don't look at the injector inheritance, I guess.

I have third-party code that imports HttpClientModule. So i'm just screwed now?

One example is swagger-codegen which imports HttpClientModule. Of course, I can change the code generator in this case, but the current behavior is generally a pitfall.

Could a warning be provided whenever this happens or some other sort of indication? It is completely unknown when this happens and why. A library (like ngx-markdown which is referenced here) can completely break an app without it being obvious why.

More Issues: