Home > Software design >  Angular: call a function of component A when the state of the routed component B has been changed
Angular: call a function of component A when the state of the routed component B has been changed

Time:12-14

The following image can help to understand what I'm going to do.

Image that shows the scenario

I have ngFor directive, in the component A, for which I route a component B binding the i-th object as state. The component B can set/change the field values of the object i-th.

I would like that when the B component change the assigned i-th object, the function of component A is called in order to make action on the other objects inside the component A.

Is there a way/mechanism/architecture that allows to do this?

The object passed as state to component B is correctly modified, in fact the modification can be viewed by component A. I don't know how to do what was described above.

Thank you all.

CodePudding user response:

You need to use a subject and observable pattern also known as event bus.

This is a summary of how it works!

  1. First we create a subject in a service, a subject can emit any number of times.
  2. Second we convert the subject to an observable in the constructor this observable will serve as a listener for events.
  3. In the service we create an emit, which can we emitted anywhere in the angular application.
  4. So ideally we have a emit method that can be called from any method in angular and a listener observable that can be subscribed from anywhere.
  5. Also not, most important, we should always unsubscribe the subscription, when using this method as it will cause a memory leak!!!!

Use case: Use this method when you need to communicate between routing, or between components that are very deeply nested from each other!

forked stackblitz

  • Related