问题描述
我有一个组件,可显示已过滤的项目列表.它订阅了两个可观察变量-第一个是用于(过滤器)参数的,需要将这些参数传递到第二个可观察变量中,以获取过滤后的项目列表.
I have a component that displays a filtered list of items. It is subscribed to two observables - the first one is for (filter) parameters that need to be passed into the second observable to get the filtered list of items.
public filteredItems = [];
this.myService.getFilterParams()
.subscribe(params => {
this.myService.getFilteredItems(params)
.subscribe(items => { this.filteredItems = items});
});
我读到链接订阅不是最佳实践(否则代码可以正常工作),那么如何重新编写呢?
I've read that chaining subscribtion is not the best practice (the code works fine otherwise), so how can I re-write it?
推荐答案
您可以使用 mergeMap
或 switchMap
来实现此目的.区别在于,如果外部订阅发出新值, switchMap
将取消内部订阅,而 mergeMap
不会取消内部订阅.
You can use either mergeMap
or switchMap
to achieve this. Difference is that switchMap
will cancel inner subscription if outer subscription emits new values, mergeMap
won't.
this.myService
.getFilterParams()
.pipe(mergeMap(params => this.myService.getFilteredItems(params)))
.subscribe(items => {
this.filteredItems = items;
});
这篇关于Angular 7:如何重新编写嵌套的订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!