2017-07-25 32 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

相关问题