typescript “错误”消息:“typeof Observable”类型上不存在“属性”“from”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47003112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:59:45  来源:igfitidea点击:

'Error' message: 'Property 'from' does not exist on type 'typeof Observable'

angulartypescriptrxjsobservableangular2-observables

提问by Deepak Pathak

I am trying to learn reactive programming using RxJS. I was trying to create an observable from an array using Observable.from()method, but I am getting an error:

我正在尝试使用 RxJS 学习反应式编程。我试图使用Observable.from()方法从数组创建一个 observable ,但出现错误:

Property 'from' does not exist on type 'typeof Observable'

类型“typeof Observable”上不存在属性“from”

I scaffolded an Angular application using Angular CLI, so all the dependencies including RxJS package was imported correctly.

我使用 Angular CLI 搭建了一个 Angular 应用程序,所以包括 RxJS 包在内的所有依赖项都被正确导入。

In app.component.tsI added below import statements:

app.component.ts 中,我添加了以下导入语句:

import { Observable} from 'rxjs/Observable'
import 'rxjs/observable/from'

And my AppComponent class looks like this:

我的 AppComponent 类如下所示:

export class AppComponent {

  numbers: number[] = [1, 2, 3, 4, 5];

  callMyObservable() : void {  
    Observable.from(this.numbers);
  }
}  

But I am getting the above mentioned compile time error.

但是我收到了上面提到的编译时错误。

I am not sure how to make it work.

我不知道如何使它工作。

回答by abaga129

If you are using rxjs >=6.0.0 then you no longer use Observable.from. Instead fromis a standalone function.

如果您使用 rxjs >=6.0.0 那么您不再使用Observable.from. 而是from一个独立的功能。

import { Observable, from} from 'rxjs';

//old way
var o = Observable.from([1, 2, 3, 4]);

//new way
var o = from([1, 2, 3, 4]);

I hope this is helpful since it took me a while to figure this out.

我希望这会有所帮助,因为我花了一段时间才弄明白。

回答by Sajeetharan

Change

改变

import { Observable} from 'rxjs/Observable'
import 'rxjs/observable/from'

To

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';