getHistory(gaaNum): void {
this.loading = true;
this.gaaHistoryService.getHistory(gaaNum)
.subscribe(atmHistory => {
// I am more sure that real data gets assigned here!!!
this.allChartData = atmHistory; // allChartData has a size of 152
this.loading = false;
}, err => {
this.loading = false;
this.errorMsg = err;
console.log(`error: ${err}`);
});
}
但是,allChartData公共变量在此处为空:
ngOnInit() {
this.allChartData = [];
this.amount= [];
this.fillSum = [];
this.barChartData = [];
this.getHistory(this.gaaNumber);
console.log(this.allChartData.length); // this is zero, allChartdata is empty here. Why?
}
如何获取超出“订阅”范围的数据?
答案 0 :(得分:3)
JavaScript是异步的,因此在编写时
this.getHistory(this.gaaNumber);
console.log(this.allChartData.length);
getHistory()
被调用-在没有时间完成之前,您已经在调用console.log(this.allChartData.length)
,它将因此打印出0。
如果您改写类似
...
this.gaaHistoryService.getHistory(gaaNum)
.subscribe(atmHistory => {
// I am more sure that real data gets assigned here!!!
this.allChartData = atmHistory; // allChartData has a size of 152
console.log(this.allChartData.length);
this.loading = false;
},
...
您将得到您想要的号码。
答案 1 :(得分:2)
如果您希望能够将其记录在ngOnInit
中,则必须使getHistory
方法成为可观察的方法。您可以通过管道传递到map
和catchError
中而不是订阅来完成此操作,然后返回结果,如下所示:
getHistory(gaaNum): void {
this.loading = true;
return this.gaaHistoryService.getHistory(gaaNum)
.pipe(map(atmHistory => {
this.allChartData = atmHistory;
this.loading = false;
}), catchError(err => {
this.loading = false;
this.errorMsg = err;
console.log(`error: ${err}`);
}));
}
现在,在您的ngOnInit
中,您可以订阅getHistory
并做您想做的任何事情。
ngOnInit() {
this.allChartData = [];
this.amount= [];
this.fillSum = [];
this.barChartData = [];
this.getHistory(this.gaaNumber).subscribe(_ => {
console.log(this.allChartData.length);
});
}