Angular Component communication using RxJS

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:
- Subject: Object which will be updated.
- Subscriber: Object which will listen to every action on Subject and do some actions. In another word, it is like an event handler function.
- Triggerer: It will update the subject.It is just a function call to update the Subject.
1. Creating the Subject:
We will be keeping the `Subject` in a Angular service like below:
2. Adding a subscriber.
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:
3. Creating the trigger.
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.