fromPromise在Observable类型上不存在 [英] fromPromise does not exist on type Observable

查看:603
本文介绍了fromPromise在Observable类型上不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用rxjs的Angular 2中,我试图将Promise转换为Observable.正如许多在线指南显示的那样,我在Observable上使用了fromPromise.哪个抛出错误:

In Angular 2 using rxjs I was trying to convert a Promise to Observable. As many of online guides showed I used fromPromise on Observable. Which throws error:

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

Observable的导入方式如下:

Observable was imported like:

import { Observable } from "rxjs/Observable";

尝试像其他运算符一样导入fromPromise会导致错误:

trying to import fromPromise like other operators results in error:

import 'rxjs/add/operator/fromPromise';

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

even if I suppress typescript error it still results in error:

(<any>Observable).fromPromise

错误:

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

rxjs存储库此处报告了类似的问题,但那里也没有解决方案

Somewhat similar issue was reported on rxjs repo here but there is no solution there either.

推荐答案

更新:

rxjs 6.0.0-beta.3开始,应从rxjs导入运算符和可观察的创建者.此外,fromPromise不再是公共API的一部分,并且包装在from方法中.

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;

更新

对于rxjs 6.0.0,请使用:

For rxjs 6.0.0 use:

import { from } from 'rxjs';

var observableFromPromise =  from(promiseSrc);

更新:

管道运算符中发布后rxjs 5.5.x,强烈建议不要使用猴子补丁方法.考虑使用静态方法选项.

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.

原始答案

rxjs 5.4.x开始,fromPromise可以用作静态方法,也可以修补到Observable原型中.

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

考虑到第二种方法基本上是第一种方法,我个人会推荐第一种方法,不同之处在于Observable原型已更改.

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.

这篇关于fromPromise在Observable类型上不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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