本文介绍了Angular 7:如何重写嵌套订阅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件可以显示过滤后的项目列表.它订阅了两个 observable - 第一个用于(过滤器)参数,这些参数需要传递到第二个 observable 中以获取过滤后的项目列表.

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?

推荐答案

您可以使用 mergeMapswitchMap 来实现此目的.区别在于,如果外部订阅发出新值,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:如何重写嵌套订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 02:09