rxjs - 外部完成时获取内部可观察对象
问题描述
我是 RxJS 的新手,所以我什至不确定我是否给了一个问题的正确标题。
解释我想要实现的目标:我有一个 API 端点,它会产生一组带有 id 的对象。然后,我将在多次调用中使用数组中的每个 id 调用另一个 API 端点。我希望第一个 API 的订阅者获取的数据已经包含第二个 API 调用的响应。
StackBlitz:https ://stackblitz.com/edit/rxjs-u45wvq
目前, 的值thatThing
是可观察的 - 我希望它们成为接收到的对象。
编辑
我设法实现了我想要的,但在我看来它看起来很脏 - 因为解决方案使用Promise
类来解决它。
https://stackblitz.com/edit/rxjs-d5ywen
如果有 RxJS 方法来做同样的事情,我会徘徊:
const source = fetchApi1().pipe(
map(x => {
return new Promise((yes, no) => {
const s = x.array.map(m => fetchApi2(m.id))
forkJoin(...s).subscribe(api2 => {
x.array.forEach((row, i) => {
row.thatThing = api2[i]
})
yes(x)
})
})
}),
switchMap(x => from(x))
);
解决方案
最好避免创建嵌套订阅,这样您就可以重写您所拥有的内容,例如以下内容:
const source = fetchApi1().pipe(
mergeMap(x => {
const s = x.array.map((m: any) => fetchApi2(m.id)
.pipe(
map(response => {
m.thatThing = response;
return m;
}),
));
return forkJoin(s).pipe(mapTo(x));
}),
);
推荐阅读
- android - Flutter:没有为“FirebaseAuth”类定义方法“signInWithGoogle”
- php - 我返回 this.http.get() 是否需要服务器的 IP 地址,以便它可以访问我的 php/json
- python - 确定两个列表的元素被分组的程度
- tensorflow - 对元组 TensorFlow 数据集进行分桶,其中每个元组元素具有不同的形状
- javascript - 当您使用新的结帐按钮时,PayPal 如何禁用浏览器的工具栏访问
- ios - 在 Swift 中创建可变或扰动计时器
- vb.net - 如何将数据连接在一行而不是两行?
- javascript - 在仅浏览器的 webapp 中管理安全身份验证
- python - 与 open 一起使用时的下拉菜单
- python - 提交 HTML 表单时的 Python Flask PUT 和 DELETE 方法