[英]Not able to add elements to an array in typescript using chart.js and bootstrat charts
我有一個奇怪的問題。 我有一個帶有映射的簡單函數,該函數試圖初始化相同對象類型的數組。 但是,迭代完成后它是空的,但是當我控制台日志時,它會打印所有對象數組。
組件中的函數
目的:
dailyStats: DailyStats[] = [];
- 功能
dailyStatistics() {
this.reportingService.dailyStats(this.toDate, this.fromDate).subscribe( r => {
r.map(res => this.dailyStats.push(res)); //console log prints the whole array all of them!
},
error => {
console.log('Failed to get Stats' + error);
},
() => {
console.log('Done getting daily stats.');
});
}
showDailyStats() {
console.log('length' + this.dailyStats.length); // length 0
for (const value of this.dailyStats) {
console.log('average' + value.average);
//this.lineChartLabels.push(value.date.toISOString());
//this.lineChartData.push({ data: [value.average], label: 'Average' });
}
}
如果在 dailyStatistics 之后調用 showDailyStats 方法,則必須使用 async/await 等待數據進入數組,然后再訪問其內容。
您可以直接在subscribe
分配異步調用的結果,而無需使用map
方法,然后調用您的方法showDailyStats
:
.subscribe( r => {
this.dailyStats = r; //console log prints the whole array all of them!
this.showDailyStats();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.