简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM