在我的项目中,我向服务器发出了多个请求,以获取单个页面的数据。我想将所有请求都设为asyc。现在,直到我收到第一个请求的响应,第二个请求的响应才被加载。
所以基本上我只想实现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));
}
这里仅显示一个请求的代码,但如构造函数所示,我一次发送多个请求。
答案 0 :(得分:0)
首先,在构造函数中调用这样的函数不是一个好习惯。
要同时运行多个请求或一起观察,请使用运算符,例如switchMap等。
关注这段与JavaScript中的事件循环相关的视频link,这将改善您的JavaScript执行,事件循环的概念。还说明了异步代码的执行方式。
希望这会有所帮助。