简体   繁体   English

使用 RxJs forkJoin 将多个 api 调用合并到单个 output 数组中

[英]using RxJs forkJoin to merge multiple api calls into single output array

Let's say I have 4 API calls.假设我有 4 个 API 调用。 In this case, each of the 4 calls return the same data structure so I don't need to manipulate the return types.在这种情况下,4 个调用中的每一个都返回相同的数据结构,因此我不需要操作返回类型。 They each return an array of objects.它们每个都返回一个对象数组。 I'd like to call them all, but combine them into on output array.我想将它们全部称为,但将它们组合到 output 阵列中。 I tried combining forkJoin with .concat( ) but that didn't do what I expected (it put them inside of smaller arrays).我尝试将forkJoin.concat( ) 结合起来,但这并没有达到我的预期(它将它们放在较小的数组中)。

forkJoin([
  this.service.getData('something', 'somethingelse'),
  this.service.getData('something1', 'somethingelse2')
].concat()).subscribe(data => console.log(data))

Consider the following implementation: (concating the arrays is performed once data has been returned)考虑以下实现:(在返回数据后执行连接 arrays)

forkJoin([
  this.service.getData('something', 'somethingelse'),
  this.service.getData('something1', 'somethingelse2')
])
.pipe(
  map(x => x.reduce((arr, curr) => [...arr,...curr]))
)
.subscribe(data => console.log(data))

Or using ES2019 flat或者使用ES2019 flat

forkJoin([
  this.service.getData('something', 'somethingelse'),
  this.service.getData('something1', 'somethingelse2')
])
.pipe(
  map(x => x.flat())
)
.subscribe(data => console.log(data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM