0

How can I use async/await in angular to make asynchronous requests. For example call a function postDataToServer(myData) and only after it resolves call getDataFromServer()? I've read examples but still haven't gotten it down and if I could see a basic example where you make one http request and another only after the first one finishes that would help a lot.

Edit: my http requests return observables not promises, maybe async/await isn't the right choice?

Zachscs
  • 3,353
  • 7
  • 27
  • 52

2 Answers2

2

Well, if you are suing Http or HttpClient, then post and get methods are returning observable to which you can subscribe, and callback will be always executed asynchronous.

this.http.post(url, body).subscribe(
   (res) => { 
      // you can just simply call another function which will make request
      this.getData();
      // or just make another request
      this.http.get(url).subscribe(...);

   }


private getData() {
   this.http.get(url).subscribe(...)
}
Patryk Brejdak
  • 1,571
  • 14
  • 26
  • can you write a snippet where you write one request then another request after? I am using Http. – Zachscs Dec 22 '17 at 18:31
  • @ZacharySchwatz Look at it now. Basically every `Observable` is resolving `asynchronous`. But if you would like to make it `synchronous` you can just convert `Observable` to `Promise` – Patryk Brejdak Dec 22 '17 at 18:35
2

This really depends on the structure of your application, but you could use async/await to do this:

async postAndGetData() {
  await this.http.post(postUrl, postData).toPromise();
  return this.http.get(getUrl).toPromise();
}

I will say that it would make sense for your post request to return the data you need so you wouldn't have to create a subsequent get request.


Another way to do this would be to have a service that holds your data in observables and use the async pipe:

<!-- template -->
{{ postService.data | async }}

@Injectable()
export class PostService {
  data = new Subject;
  constructor(private http: HttpClient) { }

  loadData() {
    this.http.get(getUrl).map(response => data.next(response));
  }
  postDataToServer(myData) {
    this.http.post(postUrl, myData).switchMap(() => this.loadData());
  }
}
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405