0
votes

In my project to learn Angular. I ran a function that returns multiple values using RxJS.

The problem is that I found that using several subscribers it comes down to Subscribe hell ...

I tried with SwitchMap, it worked for the first returned value, but I have to use that last returned value to return other values. the problem is that it returns me undefined value. I think I misused switchMap ...

(I will put the 2 versions of my function) :

Working method but with multiple Subscribe :

addToCart2() {
    const { quantity } = this.productForm.value;
    const sessionCart = sessionStorage.getItem('cart_Session');

    // Get Cart ID from SessionStorage
    this.cartService
      .retrieveCart(sessionCart!)
      .subscribe(({ id: cart_ID }: Cart) => {
        console.log('ID Cart : ', cart_ID);
        console.log('Cart Already init');

        // Add to cart method
        this.cartService
          .addToCart(cart_ID, this.product_ID, quantity, this.variant_Data)
          .subscribe(
            () => {
              // Get current cart items to send Total items to Header
              this.cartService.retrieveCart(cart_ID).subscribe((items) => {
                this.cart_Items = items.line_items;
                this.total_Items = items.total_unique_items;
                this.cartService._totalItems$.next(this.total_Items);
              });
              // Modal Success TODO !!
            },

            (err) => {
              console.log('Error in Request !!!', err);
            },

            () => {
              console.log('Add to Cart Finish.');
            }
          );
      });
  }

Using SwitchMap but not working completely :

addToCart__NotWorking() {
// Test
const { quantity } = this.productForm.value;
const sessionCart = sessionStorage.getItem('cart_Session');

this.cartService
  .retrieveCart(sessionCart!)
  .pipe(
    switchMap(({ id: cart_ID }) => {
      console.log('SwitchMap', cart_ID);
      return this.cartService.addToCart(
        cart_ID,
        this.product_ID,
        quantity,
        this.variant_Data
      );
    }),
    switchMap(({ id: cart_ID }) => {
      return this.cartService.retrieveCart(cart_ID);
    })
  )
  .subscribe((values) => {
    console.log('SwitchMap Final True : ', values);
  });

}

1

1 Answers

0
votes

Yes, you seem to be loosing the cart_id between the switchMaps, return this.cartService.addToCart does not return the id, at least according to your nested switchmaps, you instead there use the same cart id which you pass to addToCart. What you can do, is to use mapTo as you don't seem to need the response returned by this.cartService.addToCart. So, you could do:

switchMap(({ id: cart_ID }) => {
  console.log('SwitchMap', cart_ID);
  return this.cartService.addToCart(
    cart_ID,
    this.product_ID,
    quantity,
    this.variant_Data
  ).pipe(
     mapTo({ id: cart_ID }) // here, now it returns the id!
   );
}),
// .....