最佳实践——使用 switchMap 而不是多个 Subscribe

Best Practices -- Use switchMap instead of multiple Subscribe

在我的项目中学习Angular。我 运行 一个使用 RxJS return 多个值的函数。

问题是我发现使用多个订阅者归结为订阅地狱...

我尝试使用 SwitchMap,它适用于第一个 returned 值,但我必须将最后一个 returned 值用于 return 其他值。问题是它 return 是我未定义的值。我想我误用了 switchMap ...

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

工作方法,但有多个订阅:

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

正在使用 SwitchMap 但无法完全工作:

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

}

是的,你似乎失去了 switchMaps 之间的 cart_id,return this.cartService.addToCart 没有 return id,至少根据你的嵌套订阅,你在那里使用您传递给 addToCart 的相同购物车 ID。您可以做的是使用 mapTo,因为您似乎不需要 this.cartService.addToCart 编辑的 return 响应。所以,你可以这样做:

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!
   );
}),
// .....