Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

306
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda