【问题标题】:Rxjs 6 flatten observableRxjs 6 扁平化可观察
【发布时间】:2019-01-21 08:02:00
【问题描述】:

我需要关于如何将 Rxjs 5 转换为 Rxjs 6 的建议。

我的代码在下面,我不太清楚为什么它不起作用。

Rxjs 5

Observable.from([{amount:5},{amount:10}])
.flatMap(_ => depositService.deposit(depositAmount))
.toArray()
.subscribe(result => {
    console.log(result.length);
})

Rxjs 6

import { Observable, from, } from 'rxjs';
import { map, catchError, mergeMap} from 'rxjs/operators';
...

const source = from([{amount:5},{amount:10}]);
source
.pipe(mergeMap(_ => depositService.deposit(_.amount).toArray())
.subscribe(result => {
    console.log(result.length);
})

我收到了错误

您提供了一个无效的对象,其中需要一个流您可以提供 Observable、Promise、Array 或 Iterable。

【问题讨论】:

  • toArray 是一个运算符,因此需要将其传递给 pipe - 而不是链接到对 deposit 的调用:pipe(mergeMap(_ => depositService.deposit(_.amount)), toArray())
  • 不,没有用
  • 如果您需要进一步的帮助,将需要详细说明“无效”。

标签: angular rxjs


【解决方案1】:

我认为 toArray 是一个运算符,应该在管道中传入。

import { Observable, from, } from 'rxjs';
import { map, catchError, mergeMap, toArray} from 'rxjs/operators';
...

const source = from([{amount:5},{amount:10}]);
source
.pipe(
    mergeMap(_ => depositService.deposit(_.amount)),
    toArray()
)
.subscribe(result => {
    console.log(result.length);
})

【讨论】:

  • 我能做到,toArray()操作应该在mergeMap之后
猜你喜欢
  • 2017-10-15
  • 2019-10-18
  • 2016-05-17
  • 2017-06-11
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
相关资源
最近更新 更多