Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

305
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda