首页 > 解决方案 > Angular 8 和在订阅中设置 observable

问题描述

在第一个组件中,我有一个变量this.products,它是订阅 observable(s) 的结果。由于获取此变量的值涉及大量 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都是一样的。

标签: angularrxjsobservable

解决方案


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

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

推荐阅读