从数组可观察到在TypeScript中不起作用 [英] Observable from an array doesn't work in TypeScript

查看:32
本文介绍了从数组可观察到在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屋!

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