Apologies if this is a duplicate questions, but I am new to RxJS and Angular, and I wasn't quite sure what to search.
I have the following Angular component which has 2 nested components:
<div>
<h1>Parent Container</h1>
<nest-one></nest-one>
<nest-two></nest-two>
</div>
Each of those nested components can call the method on my service, which executes a http call:
getProduct(id: number): Observable<Product[]> {
return this.http.get('product/' + id)
.map((response: Response) => {
return response;
})
.catch(this.handleError);
}
And both nested components subscribe to this method call like so:
this.productService.getProduct(id)
.subscribe(
data => {
this.product = data;
}
);
My questions is, how can I, or is it possible to call the method getProduct
in my productService
and for both nested components' subscription to be executed, regardless of which component I call it from?
This is a simplified example of what I'm trying to do. Another option could be to have a base class and use that instead, but I want to see if this is possible or not.
You should use your parent container to handle this. Add an output to both components for when you want to load a new product an one input to pass the retrieved product down to them.
parent.ts
loadProduct$ = new Subject<string>();
product$ = this.loadProduct$.switchMap(id => this.productService.getProduct(id)).share();
parent.html
<div>
<h1>Parent Container</h1>
<nest-one [product]="product$ | async" (loadProduct)="loadProduct$.next($event)></nest-one>
<nest-two [product]="product$ | async" (loadProduct)="loadProduct$.next($event) ></nest-two>
</div>
Now both children are getting the new product regardless of which initiated the call. The share operator makes sure that there are no multiple streams and the backend is only called once. This is one way to do it - if you describe your use case more detailed, we may give you better answers.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments