Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Http Async await

I need to use async / await to call http.get

I've tried 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'.

Any solution for that?

like image 485
Brad Kiani Avatar asked Mar 04 '26 16:03

Brad Kiani


1 Answers

Almost a direct copy from https://stackoverflow.com/a/41834083/1260204 edited slightly so it focuses on toPromise instead of 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.

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. 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.

Here is an example file (named rxjs-operators.ts for this example) with some of the more commonly used methods.

// 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.

import './rxjs-operators';
like image 114
Igor Avatar answered Mar 06 '26 08:03

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!