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?

4
  • 1
    Possible duplicate of ts Property 'map' does not exist on type 'Observable<Response>' Commented Jan 25, 2017 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. Commented Jan 25, 2017 at 17:23
  • What about this? Commented Jan 25, 2017 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). Commented Jan 25, 2017 at 17:41

1 Answer 1

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';
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.