2017-07-25 50 views
0

我在Angular/Typescript項目中使用HighCharts。一般來說,它工作正常,但現在我卡住了:如何在HighCharts回調中訪問「this」的不同上下文(Angular/Typescript)

點擊某個點時,我想從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? 
         } 
        } 
       } 
      } 
     }); 
    } 
} 

我嘗試不同的事情沒有成功:

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

有了這個我也角範圍

click: this.onPointClick 

現在我是角範圍內之外,但不得不點進不去信息:

click: this.onPointClick.bind(this) 

在這裏,我也角範圍內,但沒有接入點信息:

click:() => this.onPointClick(this) 

有誰知道我可以拿點信息以及與此調用這個服務?我現在唯一能想到的就是一些全球性的dom元素,但這看起來不太好。

+0

的可能的複製[如何訪問正確的\'這\'回調裏面?](https://stackoverflow.com/questions/20279484/how-訪問正確的回調內) – Salketer

回答

1

您應該使用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 
         } 
        } 
       } 
      } 
     }); 
    } 
} 
+0

謝謝,我不知道這個點在事件中是可用的,因爲它首先只顯示它是MouseEvent的類型。我使用這樣的回調,它可以正常工作,點擊:(event)=> this.onPointClick(event)' – simdevmon

相關問題