Friday, October 18, 2019

A Subject is like an observable but it allows us to push it to emit a new data during code.

I’ll start by creating the products service and declare a product activated property of type Subject.

For demonstration proposes I’ll add some buttons which is going to toggle product activation.

Now let’s implement the onActivate method in the home component

As a subject is an observable and observer at the same time we can call .next() method directly without having to stablish a bridge to the observer as with regular Observables.

In this case I’ll pass the product name as a string to the next method. With this, I’ll be pushing a new data package with every new call to next(), in other words I’ll be using the observer part of the Subject.

Now in the App Component I’ll use the observable part of the Subject by subscribing to the subject.

Now I’ll inject the product service into the app component and in the ngOnInit method subscribing to the product Activated Subject. In here I can assign the data passed from the home component to the product activated property declared in the app component.

With this, we are using a subject to have observable and observer in one convenient object.

This is kind of is comparable to the event emitter which is part of angular.

Actually that event emitter is built on such a subject. It is a good practice to use Subjects instead of event emitter to implement cross-component communication.