Simplest way to share data between two unrelated Components in Angular

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:

  1. Data from the service should be multicasted. Each consumer component should access the same copy of the data. For this purpose, BehaviorSubject is used.
  2. We are not using observables, as they are unicast in nature. Subscribers will have their own copy of data.
  3. BehaviorSubject stores current value. Therefore, component will always read current value of data stored in BehaviorSubject.

Read full article on the Infragistics blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s