在第一个组件中,我有一个变量this.products
,这是预订可观察对象的结果。由于获取此变量的值涉及很多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.items
和this.products
是相同的。
答案 0 :(得分:2)
这是完全可以的,并且是软件工程中的一种常见模式,简称为DRY(请勿重复)。要更具体地讲Angular,您绝对应该将逻辑外包到服务中,然后从组件中订阅服务中的可观察对象,这样您就可以使用以下模式:
this.myItemsService
.itemsChanged() // where this returns the observable with all your switch mappings
.subscribe(items => this.items = items);
答案 1 :(得分:1)
正如其他人所说,使用服务是所有switchMap
的推荐做法。
以下是我提供的一项服务的示例:
在服务中
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
希望这会有所帮助。
答案 2 :(得分:1)
许多开关映射在组件中有点过多的业务逻辑。我建议在服务中进行此映射,您可以在两个组件中使用该服务方法。
// service
public getNiceProducts(): Observable<Products[]> {
return this.getProducts().pipe(
// lots of switchMapping
);
}