gpt4 book ai didi

rxjs - API 返回一个我需要解析的数组;每个项目一个请求

转载 作者:行者123 更新时间:2023-12-05 04:47:21 25 4
gpt4 key购买 nike

我有从后端返回的循环数据结构(可观察的),它看起来像:

[{
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 案例。您可能会在 this blog 中找到其他一些常见模式.

关于rxjs - API 返回一个我需要解析的数组;每个项目一个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68516731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com