I am trying to load the records from a json (ng2-charts stacked bar chart) file but the data is not loading into the charts. I am able to see the response with console.log but not able assign the json array to chart array. Please suggest me what should I do?
My component file.
import { Component, OnInit } from "@angular/core";
import { ChartOptions, ChartType, ChartDataSets } from "chart.js";
import * as pluginDataLabels from "chartjs-plugin-datalabels";
import { Label } from "ng2-charts";
import { BarChartService } from "../service/bar-chart.service";
@Component({
selector: "app-second-bar-chart",
templateUrl: "./second-bar-chart.component.html",
styleUrls: ["./second-bar-chart.component.css"]
})
export class SecondBarChartComponent implements OnInit {
public barChartData: ChartDataSets[];
public parentChartData: ChartDataSets[];
public myLabelsArray: Label[];
public barChartLabels: Label[];
constructor(private barchartservice: BarChartService) {}
ngOnInit() {
// WITH API CALL AND OBSERVABLE
this.barchartservice.getBarChartData().subscribe(res => {
console.log(res);
this.parentChartData = res;
});
}
}
my service file:
import { Injectable } from "@angular/core";
import { ChartOptions, ChartType, ChartDataSets } from "chart.js";
import * as pluginDataLabels from "chartjs-plugin-datalabels";
import { Label } from "ng2-charts";
import { HttpClient } from "@angular/common/http";
import { BarChart } from "../model/bar-chart";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
@Injectable({
providedIn: "root"
})
export class BarChartService {
public barChartData: ChartDataSets[];
public parentChartData: ChartDataSets[];
public myLabelsArray: Label[];
public barChartLabels: Label[];
private _url: string = "../../assets/dummy-chart/bar-chart-two.json";
constructor(private http: HttpClient) {}
getBarChartData(): Observable<any> {
return this.http.get<any>(this._url);
}
}
my json file:
[
{ "data": [14, 81], "label": "Male", "stack": "1" },
{ "data": [25, 72], "label": "Female", "stack": "1" }
]
Data should be loaded from the json file and reflect in the chart.Please help me.