我有一个可观察,它泵送一系列项目。我需要通过管道传输可观察对象,以便每个项目都执行 api 调用,使用 api 调用的结果更新自身,最后提供可观察对象的更新项目列表。
考虑如下所示的数组
<
[{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}]
每个项目都需要执行 api 调用,该调用会返回"new"或“旧”项目
GET/api/type/:id
返回new
/old
更新项目以获取新
type
属性上的 api 结果值返回更新后的列表
[{id: 1, 名称: 'a', 类型: '新'}, {id: 2, 名称: 'b', 类型: '旧'}, {id: 3, 名称: 'c' ,输入:'新'}]
我可以使用什么样的 rxjs
运算符来执行此操作?
最佳答案
如果您可以按顺序执行此操作,您可以尝试这样的操作
const items$ = from([{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}])
const request = async (data) => {
// data here would be any single object in your array
// and `doHttpRequest` is any function that returns the type
// given the original object
const type = await doHttpRequest(data)
return {
...data,
type
}
}
const results$ = items$.pipe(
// flatMap being used here since we're not returning
// a synchronous value from request
flatMap(request),
toArray()
);
// somewhere else in your code
results$.subscribe(value => console.log(value));
如果省略 toArray
部分,您可以将可观察对象保留为对象流,而不是最后完成的单个数组。
关于javascript - 通过管道传输可观察对象以使用 api 的结果更新项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60907063/