Injecting services in the component tree
The @Component
decorator has a providers
property similar to the @NgModule
decorator to register services with a component injector. A service that registers with the component injector can serve two purposes:
- It can be shared with its child components
- It can create multiple copies of the service every time the component that provides the service is rendered
In the following sections, we’ll learn how to apply each approach.
Sharing dependencies through components
A service provided through the component injector can be shared among the child components of the parent component injector, and it is immediately available for injection at their constructors. Child components reuse the same instance of the service from the parent component. Let’s walk our way through an example to understand this better:
- Create a new component named
favorites
inside thesrc\app\products...