【问题标题】:How to pipe an observable data in to an array of observables?如何将可观察数据通过管道传输到可观察数组?
【发布时间】:2021-03-06 00:49:47
【问题描述】:

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

考虑以下 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() 中映射和展开 observables

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

【问题讨论】:

  • 这不能使用 rxjs 完成!显然,这是不可能的。
  • 这不是rxjs的目的。
  • 为了解决这个问题,必须通过管道()进行解包!

标签: javascript angular rxjs


【解决方案1】:

你可以通过这个实现你想要的:

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

【讨论】:

  • 你能再检查一遍这个问题吗?
  • @mx_code 这不是产生你想要的结果吗?
  • 当我删除 map 和 toArray() 时它可以工作。但随后它将它们作为单独的项目/可观察对象而不是作为数组返回。
  • 我认为 toArray() 不起作用。你能再检查一次吗?
  • 我稍微重构了代码。以下在没有 toArray() 的情况下工作...this.getItems$() .pipe( mergeMap((items) => from(items).pipe(mergeMap((item) => this.getFromAnotherObservable$(item.value))), ), toArray(), ) .subscribe(console.log); 如果我删除 toArray(),这将工作。但随后可观察对象被分离而不是作为数组。
猜你喜欢
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 2019-12-31
  • 2019-09-09
  • 2019-02-25
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多