Zachscs Zachscs - 7 months ago 101
HTTP Question

Asynchronous Programming in Angular

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?

Answer Source

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(...)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download