首页 > 解决方案 > 如何以角度从图表(条形图/饼图等)上的 Json 文件中获取数据?

问题描述

现在我正在做的是直接从 ts 文件中获取数据,如下所示,使用 ng-2 图表和 chart.js:`

import { Component } from '@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';

@Component({
  selector: 'app-bar-chart',
  templateUrl: './bar-chart.component.html',
  styleUrls: ['./bar-chart.component.css']
})

export class BarChartComponent {

  barChartOptions: ChartOptions = {
    responsive: true,
  };
  barChartLabels: Label[] = ['Apple', 'Banana', 'Kiwifruit', 'Blueberry', 'Orange', 'Grapes'];
  barChartType: ChartType = 'bar';
  barChartLegend = true;
  barChartPlugins = [];

  barChartData: ChartDataSets[] = [
    { data: [45, 37, 60, 70, 46, 33], label: 'Best Fruits' }
  ];

}

`

HTML 文件:`

<div class="chart-wrapper">
    <canvas baseChart 
    [datasets]="barChartData"
    [labels]="barChartLabels"
    [options]="barChartOptions"
    [plugins]="barChartPlugins"
    [legend]="barChartLegend"
    [chartType]="barChartType">
  </canvas>
</div>

`

来源是使用 ng-2charts 和 charts.js 的 Angular Charts

所以,我现在想要显示相同的图表,但使用 json 文件意味着来自 json 虚拟数据,请帮助我实现这一点

json文件:

    [
 {
      "name": "Java",
      "data": [12, 10, 19]
    }, 
 {
      "name": "Python",
      "data": [23, 18, 20]
  }
]

标签: jsonangulartypescriptchart.jsng2-charts

解决方案


您可以转换数据:

let data = [ { "name": "Java", "data": [12, 10, 19] }, { "name": "Python", "data": [23, 18, 20] } ]
let colors = ["red","blue","green"]; // must match the array size, or include the color inside data
let chartData = data.map((x,i)=> {
 return {
  label: x.name,
  backgroundColor: colors[i],
  data: x.data
 }
})

console.log(chartData)

用于读取外部 JSON 文件:

import {readFileSync} from 'fs';

// create a function in service or the component
readJsonFile(path:string){
      return JSON.parse(readFileSync(path, 'utf8'));
}

然后您可以使用该函数获取json并将其传递给chartJS


推荐阅读