RxJS combineLatest 函数可以从 rxjs 和 rxjs/operators 中导入,两者有什么区别? [英] RxJS combineLatest function can be imported from both rxjs and rxjs/operators, what is the difference between the two?

查看:49
本文介绍了RxJS combineLatest 函数可以从 rxjs 和 rxjs/operators 中导入,两者有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The combineLatest function can be imported either from rxjs and from rxjs/operators.

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

When I import it from rxjs/operators (just like I import combineAll I get the following error:

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

我使用了以下代码片段:

I used the following code snippet:

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 导入它:

Therefore, I tried to import it from rxjs instead of rxjs/operators :

import { combineLatest } from "rxjs";

突然就成功了.很好,但谁能解释一下两者之间的区别?

And suddenly it worked. Nice, but can anyone explain what the difference is between the two?

推荐答案

  1. import { combineLatest } from "rxjs";

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

This is so-called "Observable creation method". Basically a method that returns an Observable based on the arguments you pass it (just like from() or of()). Since it return an instance of Observable it has the subscribe() method.

import { combineLatest } from "rxjs/operators";

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

This is an operator supposed to be used inside an operator chain. It's a method that returns another method that subscribes to the preceding Observable and returns another Observable that processes every value going through on its output.

这就是为什么它给你错误属性订阅"在类型上不存在.......从 combineLatest() 运算符返回的方法中不存在 subscribe() 方法(它返回另一个函数).

That's why it gives you the error Property 'subscribe' does not exist on type..... The subscribe() method doesn't exist on a method returned from combineLatest() operator (it returns yet another function).

这篇关于RxJS combineLatest 函数可以从 rxjs 和 rxjs/operators 中导入,两者有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆