rxjs - API 返回一个我需要解析的数组;每个项目一个请求
问题描述
我有从后端返回的重复数据结构(可观察),它看起来像:
[{
id:1,
userId: 111,
name: '',
children :[
{
id:3,
userId: 333,
name: '',
children: [...]
}
]
},
{
id:2,
userId:111,
name:'',
children: [...]
}]
我有另一个通过用户 ID 返回用户名的端点。我需要使用每个 ID 调用此服务并将返回的名称映射到结构。有没有什么漂亮的解决方案可以使用 RxJs 运营商实现这一目标?
解决方案
您可以尝试以下方法。有关详细信息,请参阅内联评论。
// fetchStruct is a function that returns an Observable which notifies the initial structure
const struct$ = fetchStruct();
// here we start the RxJs pipe transformation
struct$.pipe(
// when struct$ emits the initial structure we pass the control to another observable chain
// this is done via the concatMap operator
concatMap(beStruct => { // beStruct is the structure returned by the back end
// from beStruct we construct an array of Observables
// fetchName is a function that returns an Observable that emits when the name is returned
arrObs = beStruct.map(el => fetchName(el.id))
// with forkJoin we execute all the Observables in the array in parallel
forkJoin(arrObs).pipe(
// forkJoin emits when all Observables have notified and it will emit
// an array of values with the same order as arrObs
// we can therefore loop through this array to enrich beStruct with the names
map(names => {
names.forEach((n, i) => beStruct[i].name = n);
return beStruct;
})
)
})
)
这是一个非常典型的 RxJs 案例。您可能会在此博客中找到其他一些常见模式。
推荐阅读
- sharepoint-online - Sharepoint Online 中的旧版 SOAP API 与 OAuth?
- c++ - 擦除基类向量和派生类向量中的对象
- jquery - Laravel 5.5 阻止表单提交按 Enter
- python - 如何使用这样的标题组织我的数据框?
- javascript - 根据选择下拉列表值反应对象的过滤器数组
- node.js - 为什么nestjs socket.io extraHeaders 值未定义?
- reactjs - Spring React 不起作用 - 动画在 react js 中不起作用
- javascript - React JS - 本地存储、.map() 和 textarea 值的问题
- javascript - 获取数据 React js 时我需要切换按钮吗?
- amazon-web-services - 如何在 AWS 中正确重定向 URL?