简体   繁体   English

Angular中的异步编程

[英]Asynchronous Programming in Angular

How can I use async/await in angular to make asynchronous requests. 如何在angular中使用async / await发出异步请求。 For example call a function postDataToServer(myData) and only after it resolves call getDataFromServer() ? 例如,调用函数postDataToServer(myData)且仅在解析后调用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. 我已经阅读了示例,但仍然没有理解它,如果我能看到一个基本的示例,在该示例中,您只在第一个http请求完成后才发出一个http请求,这将大有帮助。

Edit: my http requests return observables not promises, maybe async/await isn't the right choice? 编辑:我的HTTP请求返回的观察值不是保证,也许异步/等待不是正确的选择?

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. 好吧,如果您使用HttpHttpClient ,则postget方法返回的是observable ,您可以subscribe该方法,并且回调将始终异步执行。

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 / await来做到这一点:

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. 我要说的是,您的post请求返回所需的数据是有意义的,因此您不必创建后续的get请求。


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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