Zachscs
Zachscs

Reputation: 3663

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?

Upvotes: 0

Views: 2383

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191729

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());
  }
}

Upvotes: 2

Patryk Brejdak
Patryk Brejdak

Reputation: 1601

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(...)
}

Upvotes: 2

Related Questions