【发布时间】:2020-11-02 14:10:03
【问题描述】:
当谈到首字母缩略词方法时,我总是陷入困境,因为我的代码遇到了一些问题。希望大家能帮帮我。
所以基本上,我在 onInit 上有 2 个功能;但是,当“fetchSalesbyDay2”运行时,this.firstResponse 正在接收未定义且不保存来自“fetchSalesbyDay1”的第一个响应
ngOnInit(): void {
this.fetchSalesbyDay1();
this.fetchSalesbyDay2();
}
fetchSalesbyDay1 = async () => {
const params = {
'reportName': 'home_report',
'query': {
'metric': 'salesByDay',
'showBy': this.period.toString(),
'startDate': parseInt(moment(this.range1sDate, 'MM-DD-YYYY HH:mm').format('X'), 10),
'endDate': parseInt(moment(this.range1eDate, 'MM-DD-YYYY HH:mm').format('X'), 10)
}
};
await this.http
.post(this.GLOBALURL + '/reports/query', params, this.httpOptions1)
.subscribe((response: any) => {
this.firstResponse = response;
});
}
fetchSalesbyDay2 = async () => {
const params = {
'reportName': 'home_report',
'query': {
'metric': 'salesByDay',
'showBy': this.period.toString(),
'startDate': parseInt(moment(this.range2sDate, 'MM-DD-YYYY HH:mm').format('X'), 10),
'endDate': parseInt(moment(this.range2eDate, 'MM-DD-YYYY HH:mm').format('X'), 10)
}
};
await this.http
.post(this.GLOBALURL + '/reports/query', params, this.httpOptions1)
.subscribe((response: any) => {
this.secondResponse = response;
this.displayandprocessWeekData(this.firstResponse, this.secondResponse);
});
}
我希望这样,一旦“fetchSalesbyDay1”完成,并且 this.firstResponse 已经有一个值,“fetchSalesbyDay2”就可以执行。 解决这个问题的最佳方法是什么?
【问题讨论】:
-
this.fetchSalesbyDay1().then(() => this.fetchSalesbyDay2()) -
您需要使用 RxJs 运算符合并两个响应。如果只有第二个响应对您的组件很重要,您可以使用 mergeMap,如果您需要两个响应来处理您的数据,您应该使用类似 combineLatest。看看here
标签: javascript angular asynchronous