问题
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:
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()orof()). Since it return an instance ofObservableit has thesubscribe()method.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