问题
I'm trying to create an observable from an array, as documentation says in https://github.com/ReactiveX/rxjs/blob/master/doc/observable.md:
import {Observable} from 'rxjs/Observable';
let theList = Observable.from(sites);
but I get:
TypeError: Observable_1.Observable.from is not a function
my goal is to use operators like reduce
or scan
over a Observable sequence, as a standard Observable
seems to not support, as below:
this.theList = new Observable(observer => {
// this works
observer.next(sites);
});
this.sub = this.theList.reduce(function() {
// this is never called
return acc;
}).subscribe(l => {
// this is never called
this.finalList = l;
});
The code can be found in this Plnkr: http://plnkr.co/edit/cKEqtp (src/app.ts
).
Thanks!
回答1:
There are multiple solutions :
1 - Import specific element
In your example, you are just importing the Observable
, however, you use the .from()
method in order to create an observable from an array. So you have to import the .from()
method if you want to use it. That is the same for the reduce
operator.
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/reduce';
2 - Import all operator and method
Observable
is being brought in from rxjs/Rx
, so pulling it in this way will automatically get you all of the operators and method.
import { Observable } from 'rxjs/Rx';
What is the difference ?
The big difference between these two approach is that you will not import all operators at once by using the first approach. It can be useful when you're working in production mode.
回答2:
You are importing the minimal Observable
:
import { Observable } from 'rxjs/Observable';
so to use from
, you need this import, too:
import 'rxjs/add/observable/from';
来源:https://stackoverflow.com/questions/38845719/observable-from-an-array-doesnt-work-in-typescript