[英]How can I wait for data to be pushed into an array before loading charts?
我正在嘗試在我的應用程序上顯示一些圖表,但它們當前未顯示,因為我在加載后將它們需要的數據推送到數組中,因此為空圖表。 在嘗試渲染我的圖表之前,有什么方法可以等待數組?
我嘗試過使用異步和等待,但我不知道我是否做錯了,或者在這種情況下它是否對我沒有幫助。 我嘗試在 this.games.getAllGames() function 的末尾加上 then ,然后在其中調用 loadCharts() function ,但這也不起作用。
export class SportsCardsComponent implements OnInit, AfterViewInit {
currentPage = 1;
chart: [];
gamesArray = [];
test = [];
constructor(
public games: GameService
) { }
ngOnInit() {
this.getGames();
}
async getGames() {
const game = await this.games.getAllGames(this.currentPage);
_.each(game.games, (gameData) => {
this.gamesArray.push(gameData);
});
}
loadCharts() {
_.each(this.gamesArray, (game) => {
console.log('hello');
this.chart = new Chart(game.id, {
type: 'doughnut',
data: {
labels: [game.homeTeam.teamName, game.awayTeam.teamName],
datasets: [
{
label: game.homeTeam.teamName + ' Vs ' + game.awayTeam.teamName,
backgroundColor: [game.homeTeam.schoolPrimaryColor, game.awayTeam.schoolSecondaryColor],
data: [game.homeTeam.totalBets, game.awayTeam.totalBets]
}
]
},
options: {
title: {
display: true,
text: game.homeTeam.teamName + ' Vs ' + game.awayTeam.teamName
}
}
});
});
}
我希望加載我的圖表,但每個人正在尋找的數組中沒有任何數據,因此圖表不會加載。
HTML:
<div class="col-lg-9 float-right" >
<!-- <div *ngIf='loading' class="d-flex justify-content-center">
<div class="spinner-border" style="width: 3rem; height: 3rem;" role="status"></div>
</div> -->
<!-- <div *ngIf="!loading"> -->
<div class="row">
<div class="col-lg-6 card-background"
*ngFor="let game of gamesArray"
>
<div class="card-surround shadow-sm">
<div>
<h2>{{game.homeTeam.teamName}}</h2>
<h2>{{game.awayTeam.teamName}}</h2>
<canvas id="{{game.id}}"></canvas>
<hr>
<p>{{game.gameTime}}</p>
</div>
</div>
</div>
</div>
<!-- </div> -->
<ngb-pagination
class="d-flex justify-content-end"
[collectionSize]="gamesArray.length"
[(page)]="currentPage"
[maxSize]="5"
[pageSize]='6'
(pageChange)='onPageChange($event)'
size="sm"
[rotate]="true"
[ellipses]="false"
[boundaryLinks]="true"
></ngb-pagination>
</div>
在模板中使用*ngIf
:
<canvas id="{{game.id}}" *ngIf="gamesArray.length"></canvas>
僅當數據在您的數組中時才會加載您的圖表。
您的圖表未加載,因為您的 canvas 沒有您的組件的參考。 而且您正在使用循環,因此我建議您對 Angular 使用chartjs包裝器。 https://www.npmjs.com/package/angular2-chartjs
您可以使用@ViewChild 來觸發您的圖表
例如,如果您在模板中有類似的東西
<div class="col-lg-6 card-background" *ngFor="let game of gamesArray;let i=index" >
<canvas baseChart [id]="i" [datasets]="ChartData" [labels]="ChartLabels" [options]="ChartOptions" [legend]="ChartLegend" [chartType]="ChartType" </canvas>
</div>
在 ViewModel 中,您可以使用
@ViewChild('#1') firstChartttt: BaseChart;
您現在擁有 object 您可以在檢查后在此處分配數據,無需重繪,而 angular 是雙向綁定
注意:但不要忘記啟動圖表數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.