传递数组到Chart.js无法正常工作,图表无法渲染

时间:2017-07-25 02:56:20

标签: javascript typescript charts chart.js chart.js2

我试图通过将数据数组传递给Chart.js来显示图表。如果我传递数组,图表根本不会渲染;好像数组都是空的。如果我将值硬编码到数组所在的位置,则图表呈现正常。 我是JavaScript / TypeScript的新手...... 我发现了这些类似的问题,但它们在我的情况下似乎不起作用:

Array not working correctly in Chartjs

How to add datas to chart js from javascript array itself?

这是我的代码。如果我删除硬编码数组并取消注释数组变量,则图表不会呈现。

  buildChart() {
var momentArr = new Array(); var weightArr = new Array(); var bmiArr = new Array();
this.weightList.forEach(elements => {
  elements.forEach(element => {
    momentArr.push(element.moment);
    weightArr.push(element.weight);
    bmiArr.push(element.bmi);
  });
})

console.log(momentArr);
console.log(weightArr);
console.log(bmiArr);

this.weightChart = new Chart(this.weightCanvas.nativeElement, {
  type: 'line',
  data: {
    labels: [1500948156623,1500948161541], //momentArr,
    datasets: [
      {
        label: 'Weight',
        borderColor: "#3cba9f",
        fill: false,
        data: [300, 280] //weightArr
      },
      {
        label: 'BMI',
        borderColor: "#8e5ea2",
        fill: false,
        data: [150, 140] //bmiArr
      }
    ]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            quarter: 'MMM YYYY'
          }
        }
      }],
      yAxes: [{
        type: 'linear',
        ticks: { beginAtZero: false}
      }]
    }
  }

});
}

仅供参考,weightList是FirebaseListObservable。

2 个答案:

答案 0 :(得分:1)

你想要做

this.weightChart.data.datasets[0].data.concat(weightArr);

this.weightChart.update();

等等其他数据集。如果concat不起作用,你想要遍历weightArr并推送到图表,然后更新。

for (var i = 0 ; i < weightArr.length; i++){
            this.weightChart.data.datasets[0].data.push(weightArr[i]);
}

this.weightChart.update();

希望这有帮助!

答案 1 :(得分:0)

事实证明问题根本不是chart.js;这是Firebase数据检索的异步特性。我添加了一个ref.on(....)并填充@john townsend在答案中提到的数组,现在它正在正确呈现。 谢谢你的帮助!