多个RxJS AJAX请求

编程入门 行业动态 更新时间:2024-10-25 00:30:40
本文介绍了多个RxJS AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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请求

本文发布于:2023-11-24 19:50:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626586.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   RxJS   AJAX

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!