网站搜索

angular - 即使在离开页面并返回添加数据后使用 destroy(),Canvas 仍然被占用


我收到错误:Canvas 已经在使用中。ID 为 ' ' 的图表必须被销毁,才能重复使用 ID 为 'MyChart' 的画布。对于每个特定的 ID,这个错误在控制台中出现约 4/5 次。我已经添加了。如果我停留在该页面并添加数据,则不会显示错误,但如果我跳转到其他页面再返回到这个组件添加数据,错误就会出现。

if (this.chart){
        this.chart.destroy(); 
        }  
this.chart = new Chart('MyChart', {
    type: 'line',
     data: {
     labels: monthLabels,
     datasets: [
      {
        label: 'Weight',
        data: weightLabels,
        backgroundColor: 'blue',
      },
    ],
  },
  options: {
    aspectRatio: 2.5,        
  },
}); 

答案#1

请添加以下代码来替代 if 条件

var exists = Chart.getChart('MyChart');
exists?.destroy();