【问题标题】:RxJS Scan in Typescript with different types for accumulator and updated value在 Typescript 中使用不同类型的 RxJS 扫描累加器和更新值
【发布时间】:2019-08-29 08:15:32
【问题描述】:

尝试使用不同类型的 RxJS 进行“输入和输出”:

a$: Subject<Request>;
b$: Observable<Pair[]>;

在我传递请求的地方,它在scan 函数中得到处理,并添加到累加器中:

this.b$ = this.a$.pipe(
  startWith([]),
  scan(this.accumulator),
  shareReplay(),
);

accumulator(acc: Pair[], modification: Request): Pair[] {
  // .... process request and add the pair derived from request to acc
  return acc
}

但是 typescript 立即开始抱怨累加器不适用于定义的类型,并且它只适用于设置 modification: any,这就像根本不写 typescript。

我对 Rx 有误解吗?当我进入运行时时,这种模式以前对我有用。

【问题讨论】:

  • 您可以使用scan&lt;T, R&gt;(...)强制类型
  • 它可能在抱怨startWith( [] )。这样,您将在流中同时拥有[]Request,您将使用scan 进行处理。要告诉扫描在累加器中以[] 开始,请使用scan(this.accumulator, [])

标签: typescript rxjs


【解决方案1】:

不知道你是否找到了答案,但你所要做的就是拆分主题和观察者定义:

https://stackblitz.com/edit/typescript-rxjs-scan

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多