简体   繁体   English

Angular 2 Http Async等待

[英]Angular 2 Http Async await

I need to use async / await to call http.get 我需要使用async / await来调用http.get

I've tried https://labs.encoded.io/2016/12/08/asyncawait-with-angular/ 我试过https://labs.encoded.io/2016/12/08/asyncawait-with-angular/

but

async getPrice(currency: string): Promise<number> {
  const response = await this.http.get(this.currentPriceUrl).toPromise();
  return response.json().bpi[currency].rate;
}

toPromise()

gives me an error : 给我一个错误:

[ts] Property 'toPromise' does not exist on type 'Observable'. [ts]属性'toPromise'在'Observable'类型中不存在。

Any solution for that? 任何解决方案?

Almost a direct copy from https://stackoverflow.com/a/41834083/1260204 edited slightly so it focuses on toPromise instead of map . 几乎从https://stackoverflow.com/a/41834083/1260204直接复制编辑,因此它专注于toPromise而不是map


The RxJs library has many operators that you can use like toPromise , map , catch , do , etc but in order to use these you must reference the files/modules that they are contained in. RxJs库有许多运算符,你可以使用toPromise ,如toPromisemapcatchdo等,但为了使用它们,你必须引用它们所包含的文件/模块。

The tutorials on the angular site have a good explanation on how you consume the Observable<T> and how to create a reference mapping to the more common methods you want to use like toPromise in the RxJs lib. 对角站点上的教程对你如何消费的一个很好的解释Observable<T>以及如何创建一个参考映射到要像使用更常用的方法toPromiseRxJs库。 By creating a single file with references to the more commonly used operators and types in the RxJs library you only have to then reference that reference file where you want to consume those types which saves on having to re-add all the operators/types in every file across your project where you want to take advantage of them. 通过创建一个单独的文件,引用RxJs库中更常用的运算符和类型,你只需要引用那个你想要使用那些类型的引用文件,这样就不必重新添加每个运算符/类型。在您希望利用它们的项目中的文件。

Here is an example file (named rxjs-operators.ts for this example) with some of the more commonly used methods. 下面是一个示例文件(本例中名为rxjs-operators.ts ),其中包含一些常用的方法。

// Observable class extensions
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/throw';

// Observable operators
import 'rxjs/add/operator/toPromise'; // <=== your missing extension 
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';

To the top of your file you want to use .toPromise (or any other method) add this line. 要在文件顶部使用.toPromise (或任何其他方法)添加此行。

import './rxjs-operators';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM