javascript - Angular 中的 Chart.js 图表在调整浏览器窗口大小之前不会加载
问题描述
我目前正在从事一个爱好项目,我从 MongoDB 数据库加载一些数据,从 node.js 后端获取数据到我的前端,在那里我操作我的数据,最后我想在我的 Angular 前端显示数据在 Chart.js 图表中。
问题是:我得到的数据没有任何问题,如果我用一些模拟数据加载图表,一切正常,但是当我尝试在我的图表中加载真实数据时,它不会显示,直到我调整窗口大小或例如按 f12 检查我的网站。
提前致谢!
这里有一个简化的代码:
allTitles = [];
allSets = [];
allColors = [];
// OnInit:
this.chart = new Chart('myChart', {
type: 'doughnut',
options: {
responsive: true,
},
data: {
labels: this.allTitles,
datasets: [
{
label: 'My First dataset',
data: this.allSets,
backgroundColor: this.allColors,
borderColor: '#000000'
}
]
}
});
// A Function to get the Data from my Service:
this.parseService.getPlans().subscribe((plans: any) => {
plans.forEach(plan => {
this.parseService.getExercisesByPlan(plan._id).subscribe((exercises: any) => {
this.neighbourSetsCounter = 0;
exercises.forEach(exercise => {
this.neighbourSetsCounter += exercise.sets;
});
this.allTitles[this.neighbourCounter] = plan.title;
this.allSets[this.neighbourCounter] = this.neighbourSetsCounter;
this.allColors[this.neighbourCounter] = plan.color;
this.neighbourCounter++;
});
});
});
解决方案
对这 3 个数组的引用
allTitles = [];
allSets = [];
allColors = [];
图表中使用的这些在getExercisesByPlan
发生时不会更新,并且 Angular ChangeDetector 不知道它需要检测更改并可能更新标记。您更改数组的元素,但属性内部仍然具有相同的引用。
如果它难以理解,请不要担心——当时,c++ 引用和指针是学生决定改变职业道路并放弃软件开发的主要原因:D 您将从下面的解决方案中得到它。
可能的解决方案是创建一个新数组:
this.allTitles = [...this.neighbourCounter, plan.title];
this.allSets = [...this.neighbourCounter, this.neighbourSetsCounter];
this.allColors = [...this.neighbourCounter, plan.color];
推荐阅读
- mysql - SQL: COUNT() + JOIN() 计算每个类别的项目,包括空类别
- flutter - Appbar 下方的 FLUTTER Snackbar 或 toast
- apache-poi - 将单元格添加到现有的 Apache Poi 行
- linux - 如何在 Powershell REPL 控制台中打印 xml 元素及其属性的列表?
- python - Python开发的纵横交错游戏-添加随机输入功能
- html - Angular 11.0.3 中的 ngClass 错误(无法绑定 ngClass,因为它不是 div 的已知属性)
- laravel - 无法在 laravel 中使用 mailtrap 发送电子邮件
- bash - 在 bash 脚本中输入命令
- node.js - nodejs mongoose 错误 TS2551:“文档”类型上不存在属性“isDeleted”。你的意思是'$isDeleted'
- mysql - 根据两个表的几个条件计算出现次数