Angular中的异步编程

时间:2017-12-22 18:27:51

标签: javascript angular http asynchronous async-await

如何在angular中使用async / await来发出异步请求。例如,只有在解析调用postDataToServer(myData)之后才调用函数getDataFromServer()?我已经阅读了一些例子,但仍然没有把它弄下来,如果我能看到一个基本的例子,你发出一个http请求而另一个只有在第一个完成之后才会有所帮助。

编辑:我的http请求返回observables而不是promises,也许async / await不是正确的选择?

2 个答案:

答案 0 :(得分:2)

好吧,如果您起诉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(...) } ,回调将始终以异步方式执行。

toggleClass('glyphicon-remove glyphicon-ok')

答案 1 :(得分:2)

这实际上取决于您的应用程序的结构,但您可以使用async / await来执行此操作:

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

我会说,post请求返回您需要的数据是有意义的,因此您不必创建后续的获取请求。

另一种方法是使用一个服务将数据保存在observables中并使用异步管道:

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