如何解决合并连续的观测值
我的问题是将两个连续的可观察变量组合在一起,并将其作为单个可观察变量返回。 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
})
是否有更好的运算符或其他方法可以做到这一点?
解决方法
我相信您想以一种简单的方式获得{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);
})
,
您可以使用 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运算符。
快乐编码..:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。