首页 > 解决方案 > 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++;
      });
    });
  });

标签: javascriptangulartypescriptchart.js

解决方案


对这 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];

您还可以手动触发变更检测:在 Angular 中手动触发变更检测


推荐阅读