Search⌘ K

Sharing Dependencies through Components

Explore how to share services among Angular components using the providers property in the @Component decorator. Understand service scope limiting by providing services through component injectors to manage instances effectively. Learn to inject and reuse services in child components to enhance modularity and maintainability in your Angular applications.

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.

Sharing dependencies through a component

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 through an example to understand this better:

  1. Create a new component named favorites inside the src\app\products folder: ...