Importing HttpClientModule in feature modules

一世执手 提交于 2019-12-11 19:44:58

问题


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.

  1. In which cases we want to import the HttpClientModule into feature modules?
  2. What would happen if we imported it into multiple feature modules which, in turn, are impoted into the root module?
  3. 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 import HttpClientModule into those few ones only?

回答1:


So, there are two ways to load modules in your root module,

  1. Adding it in imports array
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!