'Trigger combinelatest from another component

I have component A and B. In component A's ngOnInit, I load the initial data through combineLatest.

this.filteredProduct$ = combineLatest([
  this.productDataList$,
  this.productFilterApplied$,
  this.collectionFilterApplied$,
  this.statusFilterApplied$,
  this.unitPriceFilterApplied$,
  this.markUpFilterApplied$
]).pipe(...).subscribe((data) => {this.list = data;}); // list will be rendered in UI.

In component B, I have some button actions, click the button will update list in component A.

In another word, I have to call combineLatest in component A again. I am not sure how can I trigger it since they are in different components?



Solution 1:[1]

There are multiple ways, depending on your component structure:

  • For example if B is a child component of A, B can output an event using EventEmitter. In the event handler in A you can call next on a BevaviorSubject and that BehaviorSubject is part of list you give to combineLatest. You need BehaviorSubjectas it initially emits a value, otherwise combineLatestwould not fire.
  • If A and B have no relationship you can make the BehaviorSubect public in A and call nextfrom B.

Solution 2:[2]

It would be best to move the Subjects and Observables into a service. Component B can .next() those Subjects in the button click events, then the service can update the Observables which can then be consumed in Component A. This would be preferable to having the two components being coupled by referencing one anothers' members.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 daflodedeing
Solution 2 R. Salisbury