如何使用Chartjs以角度绘制Firebase数据

时间:2018-01-05 00:24:03

标签: angular firebase ionic-framework firebase-realtime-database chart.js

我的Firebase数据库中有结构like this的基本数据。在我的角度应用中,我想使用此数据绘制图表。 这是我的代码:

    import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Chart } from 'chart.js';
import {AngularFireDatabase} from 'angularfire2/database'






@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
chart = []; 
arraytoPassChart = []

  @ViewChild('lineCanvas') lineCanvas;




  constructor(public navCtrl: NavController, private db: AngularFireDatabase) { }


  ionViewDidLoad() {

      this.db.list('/percentage')
        .valueChanges()
        .map(res => {
          // do some calculations here if you want to
          return res.map(eachlLabel => eachlLabel)
        })
        .subscribe(res => {
          console.log(res)//should give you the array of percentage. 
          this.arraytoPassChart.push(res);
        })

    this.chart = new Chart(this.lineCanvas.nativeElement, {

        type: 'line',
        data: {
          labels: ["January", "February", "March", "April", "May", "June", "July"],
          datasets: [
            {
              label: "My First dataset",
              fill: false,
              lineTension: 0.1,
              backgroundColor: "rgba(75,192,192,0.4)",
              borderColor: "rgba(75,192,192,1)",
              borderCapStyle: 'butt',
              borderDash: [],
              borderDashOffset: 0.0,
              borderJoinStyle: 'miter',
              pointBorderColor: "rgba(75,192,192,1)",
              pointBackgroundColor: "#fff",
              pointBorderWidth: 1,
              pointHoverRadius: 5,
              pointHoverBackgroundColor: "rgba(75,192,192,1)",
              pointHoverBorderColor: "rgba(220,220,220,1)",
              pointHoverBorderWidth: 2,
              pointRadius: 1,
              pointHitRadius: 10,
              data: this.arraytoPassChart,// my data here, work when I type an array myself
              spanGaps: false,
            }
          ]
        }

      });



    }}

this question中,有人向我解释了从firebase检索数据的正确方法。在我的代码中,当我将结果记录到控制台时,我将数据作为一个数组,我想用 Chartjs 绘制图表。

console.log(res)//should give you the array of percentage.

但是当页面加载时它不会显示数据。link for empty chart但是当我自己键入数据而不是传递数据时,它可以工作。 see here

我真的很好奇我所缺少的东西,我怀疑 Chartjs 在它拥有数据之前试图绘制图表,但我也无法找到解决这个问题的方法。如果有解决方案,我会很高兴。

1 个答案:

答案 0 :(得分:1)

在订阅中构建图表

ionViewDidLoad() {

  this.db.list('/percentage')
    .valueChanges()
    .map(res => {
      // do some calculations here if you want to
      return res.map(eachlLabel => eachlLabel)
    })
    .subscribe(res => {
      console.log(res)//should give you the array of percentage. 
      this.arraytoPassChart.push(res);
      this.makeChart();
    })
}

makeChart() {
  this.chart = new Chart(this.lineCanvas.nativeElement, {
    type: 'line',
    data: {
      labels: ["January", ...],
    }
    ...
}