首页 > 解决方案 > angular5如何提出asyc请求?

问题描述

在我的项目中,我向服务器发出了多个请求以获取单页的数据。我想让所有请求都异步。现在直到我得到第一个请求的响应,第二个请求的响应没有加载。

所以基本上我只想实现异步请求和响应,所以一个请求不会等待其他请求完成。现在它就像先到先得的时尚。但是我想从多个请求中获得第一个响应的请求应该首先加载。

这是我的组件的代码

  constructor(private _dashboardService: DashboardService) {

  this.getLineChart();
  this.todayPaymentDetails();
  this.todayPaymentMethod();
  this.rewardCustomers();
  this.getAverageBill();
  this.getItemByVolumn();
  this.getItemBySales();
} 

todayPaymentMethod(id=null){
  this.paymentMethodsLoader=0;
  this._dashboardService.getTodayPaymentMethod(id).subscribe(res =>{
    if(null != res.data && '' != res.data){
      this.location = res.data.location;
      this.payment_methods = res.data.payment_methods;
    }
    this.paymentMethodsLoader=1;
  });
}

这是我的服务代码:

getTodayTotalPayment(id)  : Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.get(environment.apiUrl + constants.API_V1 + 'today-total-payment/'+id, options)
.map(res => res.json())
.catch((error: any) => Observable.throw(error.json().error || error));

}

这里仅显示一个请求的代码,但如构造函数所示,我一次发送多个请求。

标签: asynchronousrequestangular5observableresponse

解决方案


首先,在构造函数中调用这样的函数不是一个好习惯。

要同时运行多个请求或可观察,请使用运算符,即 switchMap 等。

关注这个与 JavaScript 中的事件循环相关的视频链接,这将改进您的 JavaScript 执行、事件循环概念。还解释了异步代码是如何执行的。

希望它会有所帮助。


推荐阅读