In Angular, it is essential to know how components communicate with each other. If you use a component inside another component, they create a parent child relationship. In such a scenario, parent and child components communicate to each other in following ways:
- @Input()
- @Output()
- Temp Ref Variable
- ViewChild and ContentChild
You can learn in detail about @Input here and @Output here. In this blog post, you will learn how data can be shared between components that are not related to each other using Angular Service.
To understand this using an example, create a service. In the service, create a variable called count. Service will share value of count variable across the components. Before we create count variable, let us talk about requirement again. We want all components to access last updated value of the data shared using the service.
For this, we have to wrap the count variable in RxJS subjects. To be precise let us use BehaviorSubject.
We are using BehaviorSubject for the following reasons:
- Data from the service should be multicasted. Each consumer component should access the same copy of the data. For this purpose, BehaviorSubject is used.
- We are not using observables, as they are unicast in nature. Subscribers will have their own copy of data.
- BehaviorSubject stores current value. Therefore, component will always read current value of data stored in BehaviorSubject.
Leave a Reply