多个RxJS AJAX请求 [英] Multiple RxJS AJAX Requests
问题描述
我正在使用rxjs
发出几个http请求,但我最终希望得到一个看起来像这样的对象:
I'm using rxjs
to make several http requests and I want to end up with an object that looks something like:
{
100: {
...response from api call...
},
205: {
...response from api call...
},
...etc...
}
这是我到目前为止所拥有的:
Here's what I have so far:
const projectIds = [100, 205, 208, 300]
const source = Rx.Observable
.from(projectIds)
.flatMap(id => get(`projects/${id}/builds`))
.map(response => response['data'])
.zip(projectIds)
.toArray()
source.subscribe(pipelines => {
console.log(pipelines)
})
这给了我一个数组数组,其中第一个元素是调用的响应,第二个元素是项目的ID.
This gives me back an array of arrays where the first element is the response from the call and the second element is the id of the project.
问题在于响应与项目ID不匹配,因为响应会以不同的顺序返回,具体取决于哪个请求首先完成.
The problem is that the response doesn't match the project id as the responses come back in different orders depending on which request completes first.
我如何保留顺序(或至少知道每个响应都带有哪个projectId),同时最后还要有一个对象(当前是一个数组)?
How can I preserve the order (or at least know which projectId goes with each response) while also ending up with an object at the end (currently is an array)?
推荐答案
只需将flatMap
与elementSelector
重载一起使用:
Just use the flatMap
with elementSelector
overload:
.flatMap(
projectId => getProjectDetails(projectId),
(projectId, details) => ({ id: projectId, details })
)
function getProjectDetails(id){
return get(`projects/${id}/builds`)
.map(response => response['data']);
}
这将使您可以根据需要组合输入参数和flatMap的每个输出值,从而有效地保留上下文.如果您要求输出顺序保持不变,则可以使用.concatMap
,但是所有排放都是彼此接连而不是同时进行的.
This will let you combine the input argument and every output value from flatMap as you require, effectively preserving context. If you require the output order to stay the same you can use .concatMap
but then all emissions are done after each other instead of concurrently.
然后最后使用.reduce
将所有对象组合成一个大发射:
Then finally use a .reduce
to combine all objects back to one big emission:
.reduce((acc, curr) => acc[curr.id] = curr.details, {})
这篇关于多个RxJS AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!