我正在尝试从json (NG2图表堆叠条形图)文件加载记录,但数据没有加载到图表中。我可以使用console.log查看响应,但不能将json数组分配给图表数组。请建议我该怎么做?
我的组件文件。
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;
});
}
}我的服务文件:
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);
}
}我的json文件:
[
{ "data": [14, 81], "label": "Male", "stack": "1" },
{ "data": [25, 72], "label": "Female", "stack": "1" }
]数据应该从json文件中加载并反映在chart.Please help me中。
发布于 2019-05-28 04:53:12
欢迎来到堆栈溢出,
所以在你的问题中,json对象没有正确的结构。我在我的应用程序中使用了类似的东西。
首先,为了有一个合适的结构,创建一个定义此结构的接口,如下所示:
export interface IChartDataConfiguration {
type:string;
options:any;
data: any;
labels: any[];
legend: boolean;
}然后在组件的类中定义一个属性
barChartData: IChartDataConfiguration;尝试使用具有此结构的json对象
{
"type": "bar",
"options": {
"responsive": true,
"scales": { "xAxes": [{}], "yAxes": [{}] },
"plugins": {
"datalabels": {
"anchor": "end",
"align": "end"
}
}
},
"data": [
{ "data": [65, 59, 80, 81, 56, 55, 40], "label": "Series A" },
{ "data": [28, 48, 40, 19, 86, 27, 90], "label": "Series B" }
],
"labels":["2006", "2007", "2008", "2009", "2010", "2011", "2012"],
"legend": true
}因此,获取具有此结构的json,然后将其分配到组件类的成员中,然后再分配到模板中:
<canvas baseChart
height="60%"
[datasets]="yourComponentProperty"
[labels]="barChartData.labels"
[options]="barChartData.options"
[legend]="barChartData.legend"
[chartType]="barChartData.type">
</canvas>希望这能有所帮助。
https://stackoverflow.com/questions/56331597
复制相似问题