首页 > 解决方案 > 传递类引用的角度范围问题中的Highcharts

问题描述

我得到了呈现图表的组件,我想在格式化程序的帮助下用它看起来像这样的数据覆盖初始工具提示:

tooltip: {
  formatter: function () {
    console.log(this);
    // logs data described aboved code snippet
    console.log(this.filterService.getFilters());
    // logs undefined as its component method
  }
}

其中console.log(this)记录有关图表上悬停项目的数据,如下所示:

{
  x: "xxxxx",
  y: 94,
  color: "#58a310",
  colorIndex: 0,
  key: "xxxxx",
  series: e {proceed: null, chart: a.Chart, userOptions: {…}, tooltipOptions: {…}, 
  stickyTracking: false, …},
  point: C {series: e, color: "#58a310", y: 94, options: {…}, isNull: false, …},
  percentage: 60.256410256410255,
  total: 156,
  ...
}

我需要一些来自服务的数据,这些数据是由这个组件使用的,所以我可以使用格式化程序的箭头函数来访问它:

tooltip: {
  formatter: () => {
    // here `this` refers to component class
    console.log(this.filterService.getFilters());
    // logs filters data, which I need 
  }
}

所以我需要这两个(图表项目数据和过滤器)来执行我想要的操作,但是看不到获得它们的方法,只有一个或另一个取决于我如何声明 func。

标签: javascriptangularhighcharts

解决方案


您可以使用 IIFE 函数来存储组件引用:

tooltip: {
  formatter: (function(component) {
    return function() {
      console.log(component, this);
    }
  })(this)
}

现场演示:http: //jsfiddle.net/BlackLabel/6m4e8x0y/4808/


推荐阅读