Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing HttpClientModule in feature modules

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?
like image 792
Alexander Abakumov Avatar asked Oct 21 '25 12:10

Alexander Abakumov


1 Answers

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 ̷a̷t̷ ̷t̷h̷e̷ ̷t̷i̷m̷e̷ ̷o̷f̷ ̷b̷o̷o̷t̷s̷t̷r̷a̷p̷ ̷o̷f̷ ̷y̷o̷u̷r̷ ̷a̷p̷p̷l̷i̷c̷a̷t̷i̷o̷n̷ when these services first occurs.

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.

like image 189
Akshay Rana Avatar answered Oct 25 '25 02:10

Akshay Rana