【问题标题】:RxJS combineLatest function can be imported from both rxjs and rxjs/operators, what is the difference between the two?rxJS combineLatest 函数可以从 rxjs 和 rxjs/operators 中导入,两者有什么区别?
【发布时间】:2018-10-23 13:16:36
【问题描述】:

combineLatest 函数可以从 rxjsrxjs/operators 导入。

当我从 rxjs/operators 导入它时(就像我导入 combineAll 一样,我收到以下错误:

TS2339: Property 'subscribe' does not exist on type 'OperatorFunction<{}, [{}, number, number, number]>'

我使用了以下代码sn-p:

import { timer } from "rxjs";
import { combineLatest } from "rxjs/operators";

const timerOne = timer(1000, 2500);
const timerTwo = timer(1500, 2500);
const timerThree = timer(2000, 2500);

//when one timer emits, emit the latest values from each timer as an array
const combined$ = combineLatest(timerOne, timerTwo, timerThree);

combined$.subscribe(
     ([timerValOne, timerValTwo, timerValThree]) => console.log(`Timer One Latest: ${timerValOne}, Two Latest: ${timerValTwo}, Three Latest: ${timerValThree}`)
);

因此,我尝试从 rxjs 而不是 rxjs/operators 导入它:

import { combineLatest } from "rxjs";

突然间它起作用了。很好,但是谁能解释一下两者之间的区别?

【问题讨论】:

    标签: typescript rxjs


    【解决方案1】:
    1. import { combineLatest } from "rxjs";

      这就是所谓的“Observable 创建方法”。基本上是一种根据您传递的参数返回 Observable 的方法(就像 from()of())。因为它返回一个Observable 的实例,所以它有subscribe() 方法。

    2. import { combineLatest } from "rxjs/operators";

      这是一个应该在运算符链中使用的运算符。它是一个方法,它返回另一个订阅前一个 Observable 的方法,并返回另一个处理其输出的每个值的 Observable。

    这就是为什么它会给你错误Property 'subscribe' does not exist on type....subscribe() 方法在 combineLatest() 运算符返回的方法上不存在(它返回另一个函数)。

    【讨论】:

    猜你喜欢
    • 2022-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    相关资源
    最近更新 更多