RxJS的combineLatest函数可以从rxjs和rxjs/operators导入,两者有什么区别?

2023-12-19

The 结合最新函数可以从以下位置导入rxjs和来自rxjs/运算符.

当我导入它时rxjs/运算符(就像我导入合并所有我收到以下错误:

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

我使用了以下代码片段:

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/运算符 :

import { combineLatest } from "rxjs";

突然间它起作用了。很好,但有人能解释一下两者之间有什么区别吗?


  1. import { combineLatest } from "rxjs";

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

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

    这是一个应该在操作符链内部使用的操作符。它是一个方法,它返回另一个方法,该方法订阅前面的 Observable,并返回另一个 Observable,该方法处理其输出上的每个值。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RxJS的combineLatest函数可以从rxjs和rxjs/operators导入,两者有什么区别? 的相关文章

随机推荐