RxJS combineLatest function can be imported from both rxjs and rxjs/operators, what is the difference between the two?

北慕城南 提交于 2019-12-11 04:06:26

问题


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

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}`)
);

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:


  1. import { combineLatest } from "rxjs";

    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.

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

    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.

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).



来源:https://stackoverflow.com/questions/52950090/rxjs-combinelatest-function-can-be-imported-from-both-rxjs-and-rxjs-operators-w

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!