Angular Component communication using RxJS

Component Communication in Angular

In Angular, component communication is a very essential thing. For component communication, we use @Output() and @Input(). This works well if our application is small. But as our application grow, more and more components are added. So we have to add lots of @Output() and @Input() at many levels which becomes very difficult to manage. Debugging an issue in lots of @Output() and @Input() levels is a nightmare.

There are multiple ways to resolve this issue but in this blog we are focusing on component communication using RxJS. (RxJS is simply a library of event management).

This implementation consists of three parts:

  1. Subject: Object which will be updated.
  2. Subscriber: Object which will listen to every action on Subject and do some actions. In another word, it is like an event handler function.
  3. Triggerer: It will update the subject.It is just a function call to update the Subject.

We will be keeping the `Subject` in a Angular service like below:

We will be adding a subscriber in a component in which we would like to do the event handling. Our component will look like below:

It is just a function call to subject. It can called from any place but in our case we will be triggering it from component method.

Whenever searchItems method of UvSearchboxComponent is called it will call updateCards method of HomeService which will call it’s subscriber function i.e. searchBoxSubscription method of HomeComponent.

So this way UvSearchboxComponent will communicate with HomeComponent. It doesn’t matter where these components are in component hierarchy.

It will be just three parts, Subject, Subscriber and Triggerer.

Thank You.

Programmer who loves coding and enjoys learning new technologies. 8 years of experience in JavaScript development. Website: http://www.yuvrajpatil.com