1

Everywhere, it is recommended to register a service in root AppModule providers array and avoid using providers array of root AppComponent. When should someone register a service in root AppComponent? Any practical example. What is the advantage of registering service in root AppModule compared to root AppComponent?

Jyoti Prasad Pal
  • 1,569
  • 3
  • 26
  • 41

3 Answers3

4

When registered at the root, the provided service is created as a singleton, as opposite to providing in the component, it will be created as many instances as you use the component.

In other words:
The service injected at the root level will be accessible in the entire application.
The service provided at the component level will be available only on that component and its children.

In case you inject the service in multiple components (@Component({ ...providers: [] ..}), each will get it's own instance and their children will share that same instance.
If you inject in root level (@NgModule({ ... providers: []}), all components will share the same instance.

Read more here

Vega
  • 27,856
  • 27
  • 95
  • 103
  • Do you mean to say that if one registers a service to root AppComponent providers array, it won't be available to entire application? If not, how does it make a difference when registered to root AppModule? – Jyoti Prasad Pal Aug 27 '17 at 17:02
  • Yes was just saying the the reverse: The one injected at the root level will be accessible in the entire application. – Vega Aug 27 '17 at 17:06
  • I'm confused now. If I register a service to root AppComponent instead of root AppModule, will it be available to entire application or not? Please clarify. – Jyoti Prasad Pal Aug 27 '17 at 17:09
  • question was difference between rootComponent and rootModule not between component and module. – Sukesh Marla May 28 '20 at 19:24
  • @Suskesh, the OP accepted, because this answered *their* question. If you have a new question, there is a 'ASk question' button. – Vega May 29 '20 at 00:49
0

You can register a service in app.module or in app.component. The difference is when you register a service in app.module it can be injected as a dependency in any component and service but registering it in app.component it can be injected as a dependency only to components.

Shivang Gupta
  • 3,139
  • 1
  • 25
  • 24
-3

You can't register a service into a component. Every service need to be registered in into a module.

@NgModule({
   imports: [
       CommonModule,
       etc
   ],
   declarations: [
       AppComponent,
       Other components and stuff related to this module
   ],
   exports: [
       What you want to export if this module is imported by another
   ],
   providers: [
       YourService 
   ]

For example, i keep all my services in "CoreModule" and i just import the CoreModule in AppRoot.

Hope to help with this answer.