【发布时间】:2019-08-13 19:35:26
【问题描述】:
[如果我不清楚描述情况和我想要什么,请告诉我如何改进这个问题以便您更好地理解]
我正在更改我们之前构建的 Angular 应用程序中的图表。我们正在使用 ng2-charts。之前我们使用了两个 JSON/数组。但是 REST 服务(我无法更改,因为它来自第 3 方服务)现在已更改。新的 REST 服务如下所示。我尝试使用一个 JSON。当我的输入是 .ts 文件本身中的硬编码 json 时,我能够看到图表。
但是当我尝试从 REST(GET) 调用中获取 JSON 时,我遇到了困难。
仅供参考:当我在控制台中打印 JSON 时,我可以看到它。请看图
我收到错误:
无法读取未定义的属性“数据”
以下是两个 stackblitz 示例。 第一个是硬编码的 JSON,第二个来自 REST 调用:
https://stackblitz.com/edit/ng2-charts-line-template-iq1mia
https://stackblitz.com/edit/ng2-charts-line-template-voazjk
public summaryboardJson: Summaryboard[];
public lineChartLegend = true;
public lineChartType = 'line';
public lineChartPlugins = [];
public lineChartOptions: (ChartOptions & { annotation: any }) = {
responsive: true,
};
public lineChartColors: Color[] = [
{
borderColor: 'black',
backgroundColor: 'rgba(255,0,0,0.3)',
},
];
public lineChartData: ChartDataSets[];
public lineChartLabels: Label[];
ngOnInit() {
this.http
.get("https://api.jsonbin.io/b/5c90f7d86892a7259f084846")
.toPromise()
.then(response => {
const data = response.json();
this.summaryboardJson = data;
console.log(this.summaryboardJson);
//START: put data in Bar Chart
this.lineChartData = [
{ data: this.summaryboardJson.map(a => a.noOfDefects), label: 'Defects' },
];
this.lineChartLabels = this.summaryboardJson.map(a => a.Month);
//END: put data in Bar Chart
})
.catch(error => {
console.log(error);
return Observable.of<Summaryboard[]>([]);
});
对此有何帮助,如何使用来自 REST 调用的 JSON 来创建相同的图表?
【问题讨论】:
标签: angular typescript ng2-charts