1👍
You can transform your data :
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)
For Reading External JSON File :
import {readFileSync} from 'fs';
// create a function in service or the component
readJsonFile(path:string){
return JSON.parse(readFileSync(path, 'utf8'));
}
Then You can use the function to get the json and pass it to chartJS
- Chartjs-Remove grid lines and numbers on Chart.js
- Chartjs-Unable to draw legend at desired place in chart js
0👍
I found that the push()
method appends the given elements in the last of the array and returns the length of the new array.
Here the final code to get the data from the json file and shows it to the charts
Also I have used example of this Link
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
barData: number[]=[];
title = 'chart';
constructor(private http: HttpClient){}
ngOnInit(){
this.getData();
}
getData(){
this.http.get<number[]>("assets/data.json").subscribe(data => {
this.barData.push(...data);
})
}
barChartOptions: ChartOptions = {
responsive: true,
};
barChartLabels: Label[] = ['Apple', 'Banana', 'Kiwifruit', 'Blueberry', 'Orange', 'Grapes'];
barChartType: ChartType = 'bar';
barChartLegend = true;
barChartPlugins = [];
barChartData: ChartDataSets[] = [
{ data:[]=this.barData,
label: 'Best Fruits' }
];
}
Source:stackexchange.com