将回调函数传递给打字稿中高图图例中的labelFormatter

Passing callback function to labelFormatter in highchart legend in typescript

我正在尝试使用打字稿在 Angular2 中使用 HighCharts。

我正在尝试格式化我的图例文本,并在其旁边显示图像。 HighChart 图例有 labelFormatter 属性 提供回调函数。

http://api.highcharts.com/highcharts#legend.labelFormatter

Callback function to format each of the series' labels. The this keyword refers to the series object, or the point object in case of pie charts. By default the series or point name is printed.

但我不知道如何将打字稿中的回调函数传递给 labelFormatter 属性。

updateChart(): void {
    let newOptions = {
        legend: {
            useHTML: true,
            itemMarginBottom: 10,
            enabled: true,
            floating: true,
            align: 'center',
            verticalAlign: 'top',
            labelFormatter: (s) => this.getLegendLabel(s),
            y: 35
       }
    }
}

getLegendLabel(seriesDetails) {
    console.log(seriesDetails);
}

但是我对 seriesDetails 对象未定义。

如果我在任何地方使用 this 关键字,它指的是该组件而不是系列信息。

根据 documentation:

Callback function to format each of the series' labels. The this keyword refers to the series object, or the point object in case of pie charts. By default the series or point name is printed.

我猜你在粗箭头函数中弄错了 "this"。恕我直言,最简单的方法就是遵循文档语法 (jsfiddle):

labelFormatter: function () {
    return this.name + ' (click to hide)';
}

你应该这样写你的代码:

updateChart(): void {
    let newOptions = {
        legend: {
            useHTML: true,
            itemMarginBottom: 10,
            enabled: true,
            floating: true,
            align: 'center',
            verticalAlign: 'top',
            labelFormatter: this.getLegendLabel,
            y: 35
       }
    }
}

getLegendLabel() {
    console.log(this);
}

它将生成以下 JS 代码并按您预期的方式工作(Test 是我的类名):

Test.prototype.updateChart = function () {
    var newOptions = {
        legend: {
            useHTML: true,
            itemMarginBottom: 10,
            enabled: true,
            floating: true,
            align: 'center',
            verticalAlign: 'top',
            labelFormatter: this.getLegendLabel,
            y: 35
        }
    };
};
Test.prototype.getLegendLabel = function () {
    console.log(this);
};