【问题标题】:Angular 8 and setting observable inside subscriptionAngular 8 和在订阅中设置 observable
【发布时间】:2020-03-18 23:09:36
【问题描述】:

在第一个组件中,我有一个变量 this.products,它是订阅 observable 的结果。由于获取这个变量的值涉及到很多 swithcMap-ing 和类似的东西,我不想在第二个组件中重复所有复杂的逻辑,我也需要这个结果(不仅在 html 模板中)。是否可以为此目的执行以下操作?它工作正常,但我以前从未见过这样的模式,想知道它是否有问题。

a) 第一个组件

this.getProducts().lotsOfSwitchMapping
    .subscribe((products) => 
        {this.products = products; 
        this.setNiceItems.next(products)});

b) 第二部分

this.getNiceItems()
    .subscribe(items => this.items = items);

所以this.itemsthis.products 是一样的。

【问题讨论】:

    标签: angular rxjs observable


    【解决方案1】:

    许多 switch 映射在组件中有点过多的业务逻辑。我建议在服务中进行此切换映射,您可以在两个组件中使用该服务方法。

    // service
    public getNiceProducts(): Observable<Products[]> {
      return this.getProducts().pipe(
        // lots of switchMapping
      );
    }
    

    【讨论】:

    • 非常感谢,我会这样做的!
    【解决方案2】:

    正如其他人所说,使用服务是所有switchMaping 的推荐方法。

    这是我的一项服务的示例:

    在服务中

      productsWithCategory$ = combineLatest([
        this.products$,
        this.productCategoryService.productCategories$
      ]).pipe(
        map(([products, categories]) =>
          products.map(product => ({
            ...product,
            price: product.price * 1.5,
            category: categories.find(c => product.categoryId === c.id).name,
            searchKey: [product.productName]
          }) as Product)
        ),
        shareReplay(1)
      );
    

    然后每个组件都可以订阅这个 Observable。而且由于它使用shareReplay(1),每个订阅者都会得到相同的发射项。

    在我的代码中,我在两个组件中都使用asyncPipe 来自动执行订阅/取消订阅。

    我这里有示例代码:https://github.com/DeborahK/Angular-RxJS

    此视频也可能对您有所帮助:https://www.youtube.com/watch?v=Z76QlSpYcck

    希望这会有所帮助。

    【讨论】:

    • 非常感谢@DeborahK 非常有用且解释清楚的回复!我从未听说过 shareReplay(1),我一定会看看它以及您的链接!我会给你绿色的复选标记,但 null1 回复得更快。干杯,再次感谢!
    【解决方案3】:

    这完全没问题,是软件工程中的一种常见模式,简称为 DRY(不要重复自己)。为了更具体地了解 Angular,您绝对应该将您的逻辑外包到服务中,然后从您的组件中订阅服务中的 observable,这样您就有了一些类似的模式:

    this.myItemsService
      .itemsChanged()      // where this returns the observable with all your switch mappings
      .subscribe(items => this.items = items);
    

    【讨论】:

    • 我正在考虑一项服务,但首先需要确保我没有完全偏离轨道 - 我现在知道了,所以非常感谢您!
    猜你喜欢
    • 1970-01-01
    • 2020-06-19
    • 2020-01-26
    • 2017-11-30
    • 2018-07-13
    • 2020-04-19
    • 2018-05-23
    • 2018-12-12
    • 1970-01-01
    相关资源
    最近更新 更多