首页 > 解决方案 > 如何将可观察数据通过管道传输到可观察数组?

问题描述

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

考虑以下 observable$: getItems$() 返回以下数据:

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

所以我的问题是,如何将上面的 observable 映射到一个新的 observable 中,以便在其中映射和展开另一组 observable。

预期结果:

[
    {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);

标签: javascriptangularrxjs

解决方案


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

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

推荐阅读