0

I am confused by the following documentation related to components vs services from other modules. https://angular.io/guide/sharing-ngmodules#using-components-vs-services-from-other-modules

I understand what the documentation is stating that typical usage of importing an NgModule is to gain access to shared Components, Pipes and Directives.

It also states the following: "Importing a module with services means that you will have a new instance of that service, which typically is not what you need (typically one wants to reuse an existing service). Use module imports to control service instantiation."

This is where I am confused. My understanding of the DI system (at least in an eagerly loaded application) is that if you import a shared module with a service listed as a provider, that service will eventually be registered in the root injector. The tree of NgModule imports is flattened during complilation and each service provider in registered in root injector.

The documentation here says "Importing a module with services means that you will have a new instance of that service". This is not necessarily true.

Am I missing something here? When they refer to module, do they not mean NgModule?

Fergal Rooney
  • 1,330
  • 2
  • 18
  • 31

1 Answers1

0

if you import a shared module with a service listed as a provider, that service will eventually be registered in the root injector

With the new option provideIn in the injectable decorator, it's more efficient to use provideIn everywhere, so you can put your services files wherever you want and not provide them in modules.

Check this url is for more informations on providers and this option : https://angular.io/guide/providers

Here you can play with the provideIn option and see the injection scope : https://stackblitz.com/edit/angular-dp1ucw?file=src/app/user.service.ts

Twen
  • 302
  • 2
  • 6
  • Thanks for the info. It doesn't necessarily answer my original question though regarding importing modules with providers and the statement "Importing a module with services means that you will have a new instance of that service". While you can use providedIn in the injectable decorator, you can still technically import NgModules with providers. https://angular.io/guide/providers#providedin-and-ngmodules – Fergal Rooney Nov 02 '20 at 14:35