Register service in root AppModule or root AppComp

2019-02-20 21:39发布

问题:

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?

回答1:

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



回答2:

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.



回答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.