Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
Views
Best Practices -- Use switchMap instead of multiple Subscribe

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);
  });

}

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 subscribes, 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!
   );
}),
// .....
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!