Angular13,Chart.js,ng2-chartUpdatedatafromAPIdynamically
创始人
2024-10-21 22:30:08
0
  1. 首先,需要安装Chart.js和ng2-chart。可以通过以下命令进行安装:

npm install chart.js ng2-charts

  1. 接下来,在需要使用图表的组件中引入Chart.js和ng2-chart:
import { Component } from '@angular/core';
import { Chart } from 'chart.js';
import { ChartType, ChartDataSets } from 'chart.js';
import { Color, Label } from 'ng2-charts';
  1. 在组件中定义图表数据和选项:
export class ChartComponent {
  chartData: ChartDataSets[] = [{ data: [], label: 'Data' }];
  chartLabels: Label[] = [];
  chartOptions: any = {
    responsive: true,
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  };
  chartType: ChartType = 'line';
  chartColors: Color[] = [
    {
      borderColor: 'black',
      backgroundColor: 'rgba(255,255,0,0.28)',
    },
  ];
  chartPlugins = [];
}
  1. 在组件的构造函数中注入HttpClient和zone:
constructor(private http: HttpClient, private zone: NgZone) {}
  1. 在组件中定义一个方法,该方法将从API获取数据并更新图表:
updateChartData() {
  this.http.get('http://localhost:3000/data').subscribe((data: any) => {
    this.chartData[0].data = data;
    this.chartLabels = Array.from(
      { length: data.length },
      (_, i) => `Label ${i}`
    );
    this.zone.run(() => {
      this.chart.update();
    });
  });
}
  1. 最后,在ngOnInit生命周期钩子函数中初始化图表并调用updateChartData方法:
ngOnInit() {
  this.chart = new Chart('my-chart', {
    type: this.chartType,
    data: {
      labels: this.chartLabels,
      datasets: this.chartData,
    },
    options: this.chartOptions,
    plugins: this.chartPlugins,

相关内容

热门资讯

透视妙招!wepoker提高好... 透视妙招!wepoker提高好牌率(WePoKer辅助挂)一贯真的是有辅助技巧(哔哩哔哩)1、下载好...
透视肯定!微信微乐游戏辅助脚本... 透视肯定!微信微乐游戏辅助脚本,微信微乐辅助器使用教程(透视)都是真的是有辅助挂(哔哩哔哩)一、可以...
透视模板!hhpoker到底可... 您好,hhpoker到底可以作必弊码这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704...
现有说明如下!微乐小程序黑科技... 现有说明如下!微乐小程序黑科技,微乐自建房辅助工具(透视)都是存在有辅助工具(哔哩哔哩)1、进入到是...
透视透视!微乐小程序黑科技,微... 透视透视!微乐小程序黑科技,微乐自建房免费辅助入口在哪里(透视)其实真的有辅助攻略(哔哩哔哩)1、辅...
透视阶段!wepoker透视破... 透视阶段!wepoker透视破解版(HHpoker机器人)真是真的是有辅助软件(哔哩哔哩)1、操作简...
透视策略!aapoker怎么选... 透视策略!aapoker怎么选牌(WePoKer脚本)原来是真的有辅助软件(哔哩哔哩)1、aapok...
出乎意料的是!微乐小程序黑科技... 出乎意料的是!微乐小程序黑科技免费,微信小程序微乐为什么老输(透视)一贯是真的辅助app(哔哩哔哩)...
复盘辅助挂!微信微乐游戏辅助脚... 复盘辅助挂!微信微乐游戏辅助脚本,微乐江西小程序辅助器免费(透视)真是存在有辅助技巧(哔哩哔哩)1、...
透视秘籍!wepoker轻量版... 透视秘籍!wepoker轻量版透视系统(WePoKer透视脚本)其实真的是有辅助攻略(哔哩哔哩)1、...