3

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?

cchamberlain
  • 17,444
  • 7
  • 59
  • 72
Brad Kiani
  • 271
  • 1
  • 9
  • 20
  • 1
    Possible duplicate of [ts Property 'map' does not exist on type 'Observable'](http://stackoverflow.com/questions/41833875/ts-property-map-does-not-exist-on-type-observableresponse) – Igor Jan 25 '17 at 16:33
  • 1
    @igor - While that question looks sort of similar, it is a different error. I don't think this is a dupe. – cchamberlain Jan 25 '17 at 17:23
  • What about [this](http://stackoverflow.com/questions/38090989/property-topromise-does-not-exist-on-type-observableresponse)? – forgetaboutme Jan 25 '17 at 17:37
  • It is a dupe. You are missing the `toPromise` extension method that you need to import from the `RxJs` library. The dupe points on how you can do that in a generic manner (dupe is related to missing operator `map` from RxJs). – Igor Jan 25 '17 at 17:41

1 Answers1

6

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';
Community
  • 1
  • 1
Igor
  • 60,821
  • 10
  • 100
  • 175