如何在 HighCharts 回调(Angular / Typescript)中访问“this”的不同上下文

sim*_*mon 4 javascript callback highcharts typescript angular

我在 Angular/Typescript 项目中使用 HighCharts。通常它工作正常,但现在我卡住了:

单击某个点时,我想从 http 服务中获取有关该点的更多信息。HighCharts 提供了添加回调函数的可能性:http ://api.highcharts.com/highstock/plotOptions.series.point.events.click

问题是我需要关于点的信息(点信息绑定到“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?
                        }
                    }
                }
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的事情但没有成功:

click: function() {
    console.log('Point information ' + this.x + ' ' + this.y);
    // outside of Angular scope and service cannot be reached.
}
Run Code Online (Sandbox Code Playgroud)

有了这个,我也在 Angular 范围之外

click: this.onPointClick
Run Code Online (Sandbox Code Playgroud)

现在我在 Angular 范围内,但无法访问点信息:

click: this.onPointClick.bind(this)
Run Code Online (Sandbox Code Playgroud)

在这里,我也在 Angular 范围内,但无法访问点信息:

click: () => this.onPointClick(this)
Run Code Online (Sandbox Code Playgroud)

有人知道我如何获取点信息并以此调用服务吗?我现在唯一能想到的就是一些全局 dom 元素,但这似乎不太好。

Pie*_*Duc 5

您应该使用event通过 click 事件发送的参数并将处理程序 ( 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
                        }
                    }
                }
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)