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?
相关问题
- Angular RxJS mergeMap types
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- How to update placeholder text in ng2-smart-table?
- How to instantiate Http service in main.ts manuall
- Angular: ngc or tsc?
相关文章
- angular脚手架在ie9+下兼容问题
- angular 前端项目 build 报错 "Cannot find module 'le
- Angular Material Stepper causes mat-formfield to v
- After upgrade to Angular 9 cannot find variable in
- is there any difference between import { Observabl
- Suppress “Circular dependency detected” suppress w
- How can you get current positional information abo
- Angular material table not showing data
You can't register a service into a component. Every service need to be registered in into a module.
For example, i keep all my services in "CoreModule" and i just import the CoreModule in AppRoot.
Hope to help with this answer.
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
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.