从数组可观察到在TypeScript中不起作用 [英] Observable from an array doesn't work in TypeScript
问题描述
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);
但是我得到了
TypeError: Observable_1.Observable.from is not a function
我的目标是在Observable序列上使用像 reduce
或 scan
这样的运算符,因为标准的 Observable
似乎不支持,如下所示:
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;
});
可以在此Plnkr中找到该代码: http://plnkr.co/edit/cKEqtp ( src/app.ts
).
The code can be found in this Plnkr: http://plnkr.co/edit/cKEqtp (src/app.ts
).
谢谢!
推荐答案
有多种解决方案:
在您的示例中,您只是导入了 Observable
,但是,您使用了 .from()
方法以便从数组中创建可观察对象.因此,如果要使用 .from()
方法,则必须将其导入.这与 reduce
运算符相同.
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-导入所有运算符和方法
Observable
是从 rxjs/Rx
中引入的,因此以这种方式将其拉出将自动为您提供所有运算符和方法
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.
这篇关于从数组可观察到在TypeScript中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!