Angular 8: Component Interaction using Service

Angular 8

In Angular 8, components communicate with each other to share data such as object, string, etc..

Components are made of typescript class and html template. We often required to update data of component based on the changes of the other component. In previous articles Calling Child Method from Parent Component using Temp Ref Variable and Angular5+ Communicating from child component to parent component we understand communication from child to parent and visa versa.

When page is containing two component and we want to reflect changes to second component based on changes of first component we can achieve by using service.

I am not going through how to create component and service using cli. You can checkout that on angular.io. I have provided complete example in the end of article.

Shopping Cart example

In this example, I have created two component and one service. First component is list of items with property item contains name, price and qty. On HTML side I have added functionality of increase and decrease qty of item.

 

Here we have triggered publishChanges() method on click of buttons. We have called method of service inside method. Before that code lets have look into service code.

Above I have created subject for the observable and created method that will hit next() method of observable so whichever component has subscribe to that will get response.

In publishChanges() method we have called orderUpdated() method of service class.

Now in second component we need to subscribe to same observable which is using by first component. We usually subscribe in ngOnInit() life cycle of component. Look at the code below.

This will trigger whenever first component increase or decrease quantity of the cart item.

Complete source code is available on the Github

Let me know if any doubts in comment section. Thank you for reading

Leave a Reply

Your email address will not be published. Required fields are marked *