如何在Angular中的Chart.js上显示Firestore数据?

5kgi1eie  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(120)

在我的angular项目中,我将数据保存在firestore集合中,并希望在Chart.js的“Line Chart”中显示它们。我如何实现这一点?下面是从硬编码的值创建折线图的组件文件。

createChart(){      
    this.chart = new Chart("MyChart", {
      type: 'line', //this denotes tha type of chart    
      data: {// values on X-Axis
        labels: ['2022-05-10', '2022-05-11', '2022-05-12'], 
           datasets: [
          {
            label: "Weight",
            data: ['100','95', '80'],
            backgroundColor: 'blue'
          },            
        ]
      },
      options: {
        aspectRatio:2.5
      }          
    });
  }
lnxxn5zx

lnxxn5zx1#

import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js';
import { AngularFirestore } from '@angular/fire/firestore';

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css'],
})
export class ChartComponent implements OnInit {
  chart: Chart;
  data: any[] = []; // Your Firestore data will be stored here

  constructor(private firestore: AngularFirestore) {}

  ngOnInit() {
    this.firestore
      .collection('yourFirestoreCollection') // Replace with your Firestore collection name
      .valueChanges()
      .subscribe((data) => {
        this.data = data; // Store Firestore data in the 'data' array
        this.createChart();
      });
  }

  createChart() {
    // Format your Firestore data for Chart.js
    const labels = this.data.map((item) => item.dateField); // Replace 'dateField' with your Firestore date field name
    const values = this.data.map((item) => item.valueField); // Replace 'valueField' with your Firestore value field name

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

相关问题