【问题标题】:Best Practices -- Use switchMap instead of multiple Subscribe最佳实践——使用 switchMap 而不是多个 Subscribe
【发布时间】:2021-11-04 06:45:08
【问题描述】:

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

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

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

(我会放上我的函数的 2 个版本):

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

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

}

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-11-29
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 2012-05-03
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      相关资源
      最近更新 更多