我的问题是将两个连续的可观察变量组合在一起,并将其作为单个可观察变量返回。 rxjs中有很多合并运算符,但是文档让我感到困惑。
这是我想出的可行解决方案。但是,我觉得这样做不是提高可读性的正确方法。
const observableGetId = () => {SomeFunctionBody};
const observableGetDataWithId = (id) => {SomeAnotherFunctionBody};
observableGetId.pipe(
mergeMap((id) => {
return forkJoin([
of(id),
observableGetDataWithId(id)
])
})
).subscribe((result) => {
console.log(result[0]) // id
console.log(result[1]) // data
})
是否有更好的运算符或其他方法可以做到这一点?
答案 0 :(得分:1)
我相信您想以一种简单的方式获得{id: processedId, data: data for relevant Id}
。
您可以执行以下操作
const observableGetId = () => {SomeFunctionBody};
const observableGetDataWithId = (id) => {SomeAnotherFunctionBody};
observableGetId.pipe(
mergeMap((id) => observableGetDataWithId(id).pipe(
map(res => {return {id: id, data: res}})
)))
.subscribe((result) => {
// console.log(result.id, result.data);
})
答案 1 :(得分:1)
您可以使用 SwitchMap
做到这一点,这实际上是一种有效的方法,同时您还可以借助 catchError
添加错误处理部分
const observableGetId = () => {SomeFunctionBody};
const observableGetDataWithId = (id) => {SomeAnotherFunctionBody};
observableGetId.pipe(
switchMap((id)=> observableGetDataWithId(id).pipe(
map(res => {return {id: id, data: res}}))
catchError(err => of(null)))
).subscribe((result) => {
console.log(result.id, result.data);
}, error =>
console.log("Error Description");
);
也请查看以下文章,以更好地了解RXJS运算符。
快乐编码..:)