【问题标题】:Combine two observables inside pipe() chain在 pipe() 链中合并两个 observables
【发布时间】:2020-05-06 14:53:05
【问题描述】:

我正在使用 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 项目中的最佳位置:

  • constructor() 不是最佳实践,因为这是一个长时间运行的操作(实际上它必须做 API 请求)

  • 不推荐ngOnInit(),因为在某些时候我必须更改模板中使用的this.params

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

在模板中:

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

【问题讨论】:

  • 我没有回答你问题的第二部分。 > 因为在某些时候我应该更改模板中使用的 this.params whitch,这对在ngOnInit()中执行此过程有何影响@
  • 检查完成后,您无法更改模板中使用的值,因此将此代码移至 ngOnInit 不是最佳做法。 @Ashish Ranjan
  • 我认为不会对ngOnInit() 进行检查,此时甚至还没有创建视图。

标签: angular observable rxjs6 rxjs-observables combinelatest


【解决方案1】:

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

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

我相信,订阅 Observable、进行 API 请求,理想情况下都应该转到 ngOnInit(),除非您有一些非常具体的要求,在组件加载时不希望这些订阅。

this.params 而言,您可以使用管道tap() 分配this.params,或者在您订阅此Observable 的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 2019-07-19
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多