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

问题描述 投票:0回答:1

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

  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
      }          
    });
  }
angular typescript firebase chart.js visualization
1个回答
0
投票
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,
      },
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.