使用 angular2-highchart 绘制 JSON 数据
我想用 angular2-highcharts 绘制 JSON 文件中的数据。
假设 JSON 文件中有 X 和 Y 值,格式如下:[[[1,15],[2,16],[3,18]]]。代码如下。
@Component({
selector: 'my-app',
directives: [CHART_DIRECTIVES],
template:`{{sample}}
<center> <chart [options]="options"></chart></center>`
})
export class AppComponent {
public sample;
options:Object;
constructor(public http : Http) {
http.get('data.json')
.map(res => res.json())
.subscribe(data =>this.sample=JSON.parse(JSON.stringify(data || null)),
err=>console.log(err),
() => console.log('Completed')); {}
console.log(this.sample);
this.options = {
title : { text : 'Sample Curve' },
series: [
{ data: this.sample,
color:'red'},]
}
}
}
我获取了 .json 文件中的数据值,并将其作为模板的一部分显示,正确的值似乎被打印出来了。
然而,我的 Highchart 图表是空的。由于我对 Javascript 和 Typescript 都同样陌生,我可能没有充分利用这里的一些答案。
答案#1
你正在尝试实现简单的折线图。
折线图期望数据为以下格式-
[29.9, 71.5, 106.4, 129.2] or [[1,15],[2,16],[3,18]]
而你的 JSON 结构是这种格式
[[[1,15],[2,16],[3,18]]]
你可以这样尝试-
导入 JSONP_PROVIDERS-
import {JSONP_PROVIDERS, Jsonp} from '@angular/http';
providers: [JSONP_PROVIDERS],
在 HTML 模板中-
<chart [options]="options1"></chart>
在你的组件中-
options1: Object;
constructor(jsonp : Jsonp) {
jsonp.request('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSONP_CALLBACK').subscribe(res => {
this.options1 = {
title : { text : 'AAPL Stock Price' },
series : [{
name : 'AAPL',
data : res.json(),
tooltip: {
valueDecimals: 2
}
}]
};
});
看看这是否有帮助。
答案#2
好的,所以,图表组件的选项需要在 subscribe 方法内设置,就像上面 Sanket 发布的示例中那样。我之前没有在 subscribe 内设置。存储在 this.sample 中的值一旦超出 subscribe 方法就会恢复到初始化时的值。不过我仍然不明白为什么在模板部分值会正确显示。
