Reputation: 11
Problem description: I would like to retrieve array of products from server. For this I have a function that does the following:
getProducts(customerId): Observable<Product[]> {
this.http.get(
'http://<url>'+'?productId='+productId)
.map((responseData) => {
return responseData.json();
})
.map((products: Array<any>) => {
let result:Array<Product> = [];
if (products) {
products.forEach((product) => {
result.push(
new Product(product.id,
product.mediaId,
product.description,
product.name));
});
}
return result;
}
My question is the following: I want to retrieve the image for each product that needs to be shown along with the product name and description. In order to retrieve the image I need to call another http endpoint on the server and pass product.mediaId as the parameter. So what I am not clear about is how do I do this. Do I need to make one more http.get call for each product retrieved by the previous http.get call. What is the RxJS observable and functional way of doing this? It would be great if someone could shed some light on this issue.
Upvotes: 1
Views: 287
Reputation: 202306
I would try something like that:
getProducts(customerId): Observable<Product[]> {
return this.http.get(
'https://<url>/products?customerId='+customerId)
.map(res => res.json())
.switchMap(
products => {
var productsObs = products.map(
(product) => {
return this.http.get('https://<url>/products/'+product.id);
});
return Observable.forkJoin(productsObs);
})
.map(
(productsDetails) => {
return productsDetails.map(res=>res.json());
});
}
Here are the steps:
switchMap
operator to create a new observable to get all the details of products. For this, I will map each product to a specific request. I then use the forkJoin
operator to load all these requests in parallel and go on when every responses are received. The productDetails
I received contains a list of the details of the products. I extract for each product details from the HTTP response.Here is the corresponding plunkr: https://plnkr.co/edit/h76inQy0R8EDUgYWADCZ?p=preview.
Upvotes: 1