【发布时间】:2018-06-06 14:07:12
【问题描述】:
我已经集成了一个简单的高角图表。数据来自本地创建的以下模拟 json。
{
"title": "Mothly Average RainFall",
"subtitle": "Source: WorldClimate.com"
}
下面是我的图表组件
import { Component, OnInit, AfterContentInit, OnDestroy, ViewChild,
ElementRef } from '@angular/core';
import { chart } from 'highcharts';
import { ChartServiceService } from '../chart-service.service';
@Component({
selector: 'app-barchart',
templateUrl: './barchart.component.html',
styleUrls: ['./barchart.component.css'],
providers: [ChartServiceService]
})
export class BarchartComponent implements OnInit, AfterContentInit,
OnDestroy {
resData: any;
@ViewChild('barChartId') barChartId: ElementRef;
chart: Highcharts.ChartObject;
constructor(private chartService: ChartServiceService) { }
getJsonData() {
this.chartService.getData()
.then(response => {
this.resData = response;
console.log(this.resData.title);
})
.catch(err => err)
}
ngOnInit() {
this.getJsonData();
}
ngAfterContentInit() {
const barChart: Highcharts.Options = {
chart: {
type: 'column'
},
title: {
text: this.resData.title
},
subtitle: {
text: this.resData.subtitle
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec'],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Tokyo',
data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4,
194.1, 95.6, 54.4]
}, {
name: 'New York',
data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5,
106.6, 92.3]
}, {
name: 'London',
data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3,
51.2]
}, {
name: 'Berlin',
data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8,
51.1]
}]
};
this.chart = chart(this.barChartId.nativeElement, barChart);
}
ngOnDestroy() {
this.chart = null;
}
}
我在 resData 中获取响应 json 数据,并在访问图表组件中的标题时收到错误消息,提示无法读取未定义的属性。任何人都知道这个问题。我在 console.log 中得到的也是一样。
下面我更新的图表服务代码
import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
@Injectable({
providedIn: 'root'
})
export class ChartServiceService {
constructor(private http: Http) { }
// function to get the api response and convert to json
private getResponseData(res: Response) {
return res.json();
}
//function to handle the error from api call
private handleError(error: Response | any) {
console.error(error.message || error);
return Promise.reject(error.message || error);
}
//function to get the response data using promise
public getData(): Promise<any> {
return this.http.get('assets/mockData.json').toPromise()
.then(this.getResponseData)
.catch(this.handleError);
}
}
【问题讨论】:
-
你能给我们看看你的
ChartServiceService文件吗?我猜你没有错误地返回简单对象的地方正在发生一些事情。另外,我认为没有多少人这样做,但您可以使用resData: {title, subtitle};以便知道对象中的内容。 -
@rhavelka: 我已经添加了上面的服务代码。
-
请尝试调试“
error saying cannot read property of undefined”的来源。现场演示也不错 - 对于 Angular,您可以使用 Plunker 或 codesandbox.io 或类似的东西。
标签: angular highcharts