我遇到了无法创建图表的错误:无法从给定项目获取上下文,我认为这是因为在填充游戏数组之前调用了我的loadCharts函数,因此在模板上看不到ID。但是我不是100%。
我尝试过等待异步,不起作用,每次尝试游戏之后,我都尝试调用this.loadCharts()。我尝试过* ngIf在游戏开始之前不加载图表,但是无论我如何尝试,我似乎都无法使其正常工作。
这是组件
import { Component, OnInit, AfterContentInit, AfterViewChecked, AfterViewInit } from '@angular/core';
import { _ } from 'underscore';
import { Chart } from 'chart.js';
import { GameService } from '../../services/games.service';
@Component({
selector: 'app-sports-cards',
templateUrl: './sports-cards.component.html',
styleUrls: ['./sports-cards.component.scss']
})
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);
});
this.loadCharts(this.gamesArray);
}
ngAfterViewInit() {
this.loadCharts(this.gamesArray);
}
onPageChange(pageData) {
this.currentPage = pageData;
this.games.getAllGames(this.currentPage).then(game => {
console.log(this.currentPage);
// this.gamesArray = game;
});
}
loadCharts(gameData) {
_.each(gameData, (games) => {
console.log(games);
console.log('hello');
this.chart = new Chart(games.id, {
type: 'doughnut',
data: {
labels: [games.homeTeam.teamName, games.awayTeam.teamName],
datasets: [
{
label: games.homeTeam.teamName + ' Vs ' + games.awayTeam.teamName,
backgroundColor: [games.homeTeam.schoolPrimaryColor, games.awayTeam.schoolSecondaryColor],
data: [games.homeTeam.totalBets, games.awayTeam.totalBets]
}
]
},
options: {
title: {
display: true,
text: games.homeTeam.teamName + ' Vs ' + games.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>
这给我一个错误,无法创建图表:无法为我正在创建的每个游戏从给定项目获取上下文。游戏显示出来,但不是图表。
ngAfterViewInit ()
中显示项目相关的所有内容,以防止DOM错误。因为有时在显示内容时您的DOM不存在。根据您的模板html,您有一个微调器。因此,
ngOninit()
ngOninit()
或ngAfterViewInit()
ngAfterViewInit()
ngOninit()
的更多信息:Lifecycle Hooks在Angular首先显示数据绑定属性并设置指令/组件的输入属性后,初始化指令/组件。在第一个ngOnChanges()之后调用一次。
因此,如果您有任何@Input
装饰器,则ngOninit()
是从模板html中获取它的时间,而不是显示某些内容的时间。只是检查属性的好时机。另外,请注意,构造函数不是angular生命周期的一部分。请注意,*ngIf
将破坏您的DOM,这对隐藏您的组件不利。