javascript - 如何将可观察数据通过管道传输到可观察数组中?

标签 javascript angular rxjs

如何将可观察数据通过管道传输到可观察数组中,并将其与内部的另一个可观察数据进行映射?

考虑以下可观察$: getItems$() 返回以下数据:

[
    {item: 1, value: 'one'},
    {item: 2, value: 'two'},
    {item: 3, value: 'three'},
    ...
]

所以我的问题是如何将上述可观察量映射到一个新的可观察量,以便在其中映射并解开另一组可观察量。

预期结果:

[
    {item: 1, value: 'one', prop: 'someValueMappedFromAnotherObservableMethod1'},
    {item: 2, value: 'two',  prop: 'someValueMappedFromAnotherObservableMethod2'},
    {item: 3, value: 'three',  prop: 'someValueMappedFromAnotherObservableMethod3'},
    ...

// here someValueMappedFromAnotherObservableMethod1 is the value that should be obtained as a result of flatMapping observable inside the ```items.map()``` fn.
]

这是我尝试过的。它不起作用。它不是在 items.map()

内映射和展开可观察对象
    this.getItems$()
      .pipe(
        flatMap((items) =>
          items.map((item) => ({...item, prop: this.anotherMethodReturningObservableBasedOnItemValue$(item.value))}),
        ),
      )
      .subscribe(console.log);

但是上面的并没有按预期工作。让我知道如何做到这一点/

我也尝试过这种方法:

    this.getItems$()
      .pipe(
        flatMap((items) =>
          merge(items.map((item) => this.anotherMethodReturningObservableBasedOnItemValue$(item.value))).pipe(
            combineAll(),
          ),
        ),
      )
      .subscribe(console.log);

最佳答案

您可以通过以下方式实现您想要的:

this.getItems$()
  .pipe(
    mergeMap(items =>
      from(items)
        .pipe(
          mergeMap(item =>
            this.anotherMethodReturningObservableBasedOnItemValue$(item.value)
              .pipe(
                take(1), // toArray operator below requires all sources to complete
                map(prop => ({ ...item, prop })) // Combine new prop with existing props 
              )
          ),
          // Combine all items into single array
          toArray()
        )
    )
  )
  .subscribe(console.log);

关于javascript - 如何将可观察数据通过管道传输到可观察数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66495124/

相关文章:

javascript - 自动版本化外部链接内容

javascript - 如何在 react 中创建更多状态? react 状态的属性数量是否固定?

javascript - 在加载时调整 TextArea 的大小

Angular4 总是需要浏览器缓存清理

javascript - Angular2 - Material2 示例 : MdAutoComplete

Angular 7无法访问管理文件夹文件

javascript - RxJS 在 Ajax 错误后继续监听

javascript - 提供适合用户连接的视频 Assets ?

Angular2 和 RxJS - 缓存接受参数的服务

rxjs - observable.subscribe(..).unsubscribe();反模式。