asynchronous - 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));
}
这里仅显示一个请求的代码,但如构造函数所示,我一次发送多个请求。
解决方案
首先,在构造函数中调用这样的函数不是一个好习惯。
要同时运行多个请求或可观察,请使用运算符,即 switchMap 等。
关注这个与 JavaScript 中的事件循环相关的视频链接,这将改进您的 JavaScript 执行、事件循环概念。还解释了异步代码是如何执行的。
希望它会有所帮助。
推荐阅读
- sql - SQL中的CURSOR在其中只有1条记录时运行多次
- uwp - Windows 10 iot core UWP蓝牙声音连接
- email - PHPMailer:是否可以为密件抄送设置不同的消息 ID?
- powershell - 如何使用powershell查找和替换出现在管道分隔的csv文件中第n个位置的字符串
- parsing - 不包含 epsilon 转换的文法可以为空
- typescript - JEST:如何测试向对象添加数据
- knockout.js - 将 ko observables 组合成一个 ko observable 数组
- new-operator - 交易视图有一个分歧指标,我想了解如何有效使用警报
- java - 无法将值添加到我的嵌套 HashMap
- python - 在 django 中使用模板在表格中显示值