RxJs array of http calls

I make an http request which returns Observable with array of products. For each of this product I need to make http call in order to get the details.
How to make it in parallel using RxJs. Now I have a products.forEach and eventually get this working but this uses external (to my method) BehaviorSubject.
I’d prefer return kind of concatenated object with all the details.

    return this.apiService.getCart().pipe(
      map(({ id, products, quantity }) => {
        products.forEach(({ productId }) => this.getProduct(productId).subscribe((product) => this.cart.products.push(product)));
        return { id, quantity }
      })
    )}

>Solution :

I recommend you to use the forkJoin operator and then return the product-details array as part of an object:

return this.apiService.getCart().pipe(
    switchMap(({ id, products, quantity }) => {
        const obs = products.map(({ productId }) => this.getProduct(productId));
        return forkJoin(obs).pipe(
            map((products) => ({ id, quantity, products })),
        );
    }),
);

Leave a Reply