在管道()链中合并两个观测值。

问题描述 投票:0回答:1

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

  1. 从paramMap$中获取params,然后... ...

  2. 根据params的值,把(getData():Observable,getCategories():Observables)两个一起得到,然后......。

  3. 从([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>
angular observable rxjs6 rxjs-observables combinelatest
1个回答
2
投票

在得到params之后,要用管道传送Observable,可以使用以下方法 switchMap 并返回一个 forkJoin() 的内部。

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

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

至于 this.params 的时候,你可以指定 this.params 下要么使用管道式 tap() 或者你在哪里为这个Observable做订阅。

© www.soinside.com 2019 - 2024. All rights reserved.