我在Angular / Typescript项目中使用HighCharts。通常它可以正常工作,但是现在我被卡住了:
单击某个点时,我想从http服务获取有关该点的更多信息。 HighCharts提供了添加回调函数的可能性:http://api.highcharts.com/highstock/plotOptions.series.point.events.click
问题是我需要有关该点的信息(该点信息绑定(bind)到“this”),而且还需要在“this”指向类实例的地方调用服务。
@Component({
// ...
})
export class ChartComponent {
chart: any;
constructor(private dataService: DataService) { }
onPointClick(point: any) {
this.dataService.getPointDetails(point) // then ...
}
buildDataChart() {
let Highcharts = require('highcharts/highstock');
this.chart = new Highcharts.StockChart({
// ...
plotOptions: {
series: {
point: {
events: {
click: // How to implement this function?
}
}
}
}
});
}
}
我尝试了不同的尝试而没有成功:
click: function() {
console.log('Point information ' + this.x + ' ' + this.y);
// outside of Angular scope and service cannot be reached.
}
这样我也不在Angular范围内
click: this.onPointClick
现在,我在Angular范围内,但无法访问点信息:
click: this.onPointClick.bind(this)
在这里,我也在Angular范围内,但是无法访问点信息:
click: () => this.onPointClick(this)
有人知道我如何获取点信息并以此来调用服务吗?我现在唯一能想到的就是一些全局的dom元素,但这似乎不是很好。
最佳答案
您应该使用通过click事件发送的event
参数,并将处理程序(onPointClick
)定义为组件类的字段值。这样就不需要bind
或奇怪的this
上下文。在event
中,该点定义在event.point
:
export class ChartComponent {
chart: any;
constructor(private dataService: DataService) { }
onPointClick = (event: any) => {
this.dataService.getPointDetails(event.point);
};
buildDataChart() {
let Highcharts = require('highcharts/highstock');
this.chart = new Highcharts.StockChart({
plotOptions: {
series: {
point: {
events: {
click: this.onPointClick
}
}
}
}
});
}
}