使用 chartjs 和 firebase realtime db 创建实时折线图

Creating a real time line chart using chartjs and firebase realtime db

我正在使用 angular 7 和 chart.js 库。我根据使用 angularfire2 库从 firebase 实时数据库中提取的数据创建了一个折线图。

数据显示每小时发送的消息数。这很好用。但是,我想在数据更新时实时更新图表。

以下代码适用于静态版本。请建议

 <div style="display: block;padding-top:30px">
                <canvas baseChart
                [chartType]="'line'"
                [datasets]="chartData"
                [colors]="colors"
                [labels]="chartLabels"
                [options]="chartOptions"
                [legend]="true">
                </canvas>
              </div>

对于 .ts

@ViewChild(BaseChartDirective, null)
  public chart: BaseChartDirective;

 chartOptions = {
    responsive: true,
    legend: {
      display: true
   },
   scales: {
    yAxes: [{
        ticks: {
            beginAtZero: true
        }
    }]
    }
  };


  chartData = [
    { data: [], label: 'Messages/hour'
  }
  ];

  colors = []
  chartLabels = [];

async ngOnInit() {

    let resp = await this.dataSvc.fetchHourlyMessages(this.core.orgName)

    for(let key of Object.keys(resp)){
      this.chartData[0].data.push(resp[key].messages)
      let hour = resp[key].hour
      this.chartLabels.push(hour)
    }
    this.chart.chart.update()

  }

服务是:

fetchHourlyMessages(orgName:string){

    return new Promise((resolve, reject) =>
    {
      this.db.list(orgName + '/stats/messages/hourly/', ref => ref.orderByChild("messages").limitToLast(12)).valueChanges().subscribe(
        (res) => {
                    resolve(res)},
        (err) => { 
                    console.log("hitting error:" + err); reject(err)
                }
      )
   })

  }

数据如下所示

/stats
    /messages
       /hourly
         /1pm
           messages: 3
           hour: 1pm
         /2pm
           messages: 4
           hour: 2pm

所以这里发生的是你只调用这个函数一次,因为你做出了承诺。 你所要做的就是使用观察者。观察者将 return 套接字的值和更改后的值与 firebase 的 valueChanges 选项。为此,您必须更改服务:

fetchHourlyMessages(orgName:string){
  return this.db.list(orgName + '/stats/messages/hourly/', ref => ref.orderByChild("messages").limitToLast(12))
}

在你的 ngOnInit 上:

  this.dataSvc.fetchHourlyMessages(this.core.orgName).valueChanges().subscribe((resp: any) => {

    for(let key of Object.keys(resp)){
      this.chartData[0].data.push(resp[key].messages)
      let hour = resp[key].hour
      this.chartLabels.push(hour)
    }
    this.chart.chart.update()
  });