【问题标题】:using RxJs forkJoin to merge multiple api calls into single output array使用 RxJs forkJoin 将多个 api 调用合并到单个输出数组中
【发布时间】:2021-03-28 16:02:17
【问题描述】:

假设我有 4 个 API 调用。在这种情况下,4 个调用中的每一个都返回相同的数据结构,因此我不需要操作返回类型。它们每个都返回一个对象数组。我想将它们全部称为,但将它们组合到输出数组中。我尝试将forkJoin.concat( 结合起来,但这并没有达到我的预期(它将它们放在较小的数组中)。

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

【问题讨论】:

  • 让我看看我是否理解......每个电话都会给你类似 [{a:1 b:1}, {a:2,b:2}] 和 [{a:3 b :3}, {a:4,b:4}]... 你想要 [{a:1 b:1}, {a:2,b:2}, {a:3 b:3}, { a:4,b:4}] 作为最终输出?
  • 是的。一个数组,它获取每个内部数组的所有对象并将它们放入单个数组输出中。我可以将 forkJoin 与字典语法一起使用,并将每个返回 Object 转换为一个数组,但鉴于所有 RxJ 都可以做到,这似乎是不必要的。我只是不知道在哪个连续使用哪个运算符。
  • 好吧.. 如果你这样做:forkJoin([ this.service.getData('something', 'somethingelse'), this.service.getData('something1', 'somethingelse2') ]).subscribe(data => console.log(data[0].concat(data[1])))

标签: angular rxjs


【解决方案1】:

考虑以下实现:(在返回数据后执行连接数组)

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))

或使用ES2019 flat

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多