首页 > 解决方案 > 在 pipe() 链中合并两个 observables

问题描述

我正在使用 Rxjs,我想从以下模式(按顺序)创建一个 Observable:

  1. 从 paramMap$ 获取参数,然后...

  2. 根据 params 的值,将两者 (getData():Observable, getCategories():Observables) 放在一起,然后......

  3. from ([data, categories]) 创建最终对象。

代码如下所示:

//route = this.ActivatedRoute

let obs$ = route.paramMap.pipe(

// combineLatest() is not a pipable operator, so it shouldn't be used inside .pipe()
// also it doesn't accept a function,
// but this just to show you what I want to do.

combineLatest(params=>getData(params.id), params=>getCategories(params.id)),

map(([data, categories])=>{
//do some changes...
return {data,categories}
}
)
)

将此代码放在 Angular 项目中的最佳位置是哪里:

...
combineLatest(params=>
   getData(params.id).pipe(
        map(data=>{
            this.params.type=data.type; 
            return data
           })), 
   params=>getCategories(...) 
)

在模板中:

<div>{{params.type}}</div>

标签: angularobservablerxjs6rxjs-observablescombinelatest

解决方案


要在获取参数后对 Observable 进行管道传输,您可以在其中使用switchMap并返回 a forkJoin()

this.route.paramMap.pipe(switchMap((params) => {
    return forkJoin(getData(params.id), getCategories(params.id));
}));

我相信,订阅一个 Observable,做 API 请求,最好都应该去ngOnInit()除非你有一些非常具体的要求,在组件加载时你不希望这些订阅。

this.params目前而言,您可以this.params在使用管道tap()或订阅此 Observable 的地方进行分配。


推荐阅读