Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 })),
        );
    }),
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading