问题
The docs on HttpClientModule
say:
Before you can use the HttpClientModule, you need to import the Angular HttpClientModule. Most apps do so in the root AppModule.
- In which cases we want to import the
HttpClientModule
into feature modules? - What would happen if we imported it into multiple feature modules which, in turn, are impoted into the root module?
- Is this a proper use case of it when we have dozens of modules in an app, a few of which need
HttpClientModule
, and we would like to importHttpClientModule
into those few ones only?
回答1:
So, there are two ways to load modules in your root module,
- Adding it in imports array
- Lazy Loading
Now when you load a module in imports array, all the services provided by that module become singleton services, that is, only single instance of those services will be shared throughout your application. And the instance of those services are created by root injector at the time of bootstrap of your application.
In terms of services, it does not matter if you load a module in root module or multiple feature modules, and then you load all those feature modules in your root module, you will end up with single instances of the services.
But, in terms of your declarations, i.e. Components, Pipes, directives. If you want to use an AModule for the components it exports, you will have to load AModule in the feature module in which you want to use the components.
But, you can look at the HttpClientModule source_code. there is nothing in the declarations or exports array. It only provide services, so it does not matter if you load it in your feature module(while loading the feature module in root module's imports array), or in Root module, you will get it's services either way. So, just load it in the Root Module.
Now when you use Lazy loading to load a feature module, the lazily loaded module does get all the services provided by all other modules in the root module, but it has it's own injector, that means if you load HttpClientModule in the lazily loaded module which is already loaded in root module, you will end up with two instances of all the services provided by HttpClientModule, and you don't want that.
You can further read more about forRoot and forChild pattern to tackle such situations.
来源:https://stackoverflow.com/questions/57187673/importing-httpclientmodule-in-feature-modules