不存在于可观测类型

在角度2中使用 rxjs 我试图将一个承诺转换为可观测的。正如许多在线指南所显示的那样,我在 Observable上使用了 fromPromise。这引发了错误:

Property 'fromPromise' does not exist on type 'typeof Observable'.

进口的可观测数据是这样的:

import { Observable } from "rxjs/Observable";

试图像其他操作符一样导入 fromPromise会导致错误:

import 'rxjs/add/operator/fromPromise';

即使我抑制打印错误,它仍然会导致错误:

(<any>Observable).fromPromise

错误:

Uncaught (in promise): TypeError: __WEBPACK_IMPORTED_MODULE_3_rxjs_Observable__.Observable.fromPromise is not a function

在 rxjs repo 给你上也出现了类似的问题,但是也没有解决方案。

62008 次浏览

UPDATE:

As of rxjs 6.0.0-beta.3, operators and observable creators should be imported from rxjs. Furthermore, fromPromise is not part of the public API anymore and its wrapped in the from method.

TL;DR;

UPDATE

For rxjs 6.0.0 use:

import { from } from 'rxjs';


var observableFromPromise =  from(promiseSrc);

UPDATE:

After the release of the pipeable operators in rxjs 5.5.x, the monkey patch approach is strongly discouraged. Consider to use the static method option.

Original answer

As of rxjs 5.4.x, fromPromise can be used as a static method or can be patched into the Observable prototype.

For the first, you can do the following:

import { fromPromise } from 'rxjs/observable/fromPromise';


var observableFromPromise = fromPromise(promiseSrc);

More info about this approach here

To do the second, you need to change your import statement:

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


var observableFromPromise = Observable.fromPromise(promiseSrc);

More info about this approach here

Personally I would recommend the first one, considering that the 2nd approach is basically the 1rst, with the difference that the Observable prototype is changed.

like what Jota said 'from' is the answer.

you can find the reference from here

https://www.learnrxjs.io/operators/creation/from.html

However, if you want to specify 'Promise to Observable' you could use 'fromPromise' like below.

  import { from as fromPromise, Observable} from 'rxjs';
...


private getObservable(): Observable<any> {
return fromPromise(this.promise);
}




private getPromise() {


this.promise = new Promise((resolve, reject) => {
this.service.getPromise()
.then(response => {
//  do sth
resolve(response);
});
});
}