使用Angular4将侦听器添加到Amcharts

时间:2017-05-31 07:30:00

标签: javascript angular listener amcharts

我正在尝试在angular4项目中的Amcharts Piechart上实现向下钻取功能。 official wrapper具有在配置对象中添加侦听器的功能。然后将此配置对象传递给AmChartsService以生成图表。

我的问题在这里:

import { AmChartsService } from "@amcharts/amcharts3-angular";

@Component({
  template: `<div id="chartdiv" [style.width.%]="100" [style.height.px]="500"></div>`
})
export class AppComponent {
  private chart: any;

  constructor(private AmCharts: AmChartsService) {}

  public whatever(){}

  ngOnInit() {
    this.chart = this.AmCharts.makeChart("chartdiv", {
      "type": "pie",
      "theme": "light",
      "dataProvider": [],
      "listeners": [{
                event: 'clickSlice',
                method: function(event) { 
                     this.whatever()<--- HERE
                }
        }],
      ...
    });
  }
}

我无法调用javascript函数范围之外的方法。他们的tutorial表明它是使用javascript完成的,但没有迹象表明如何在像我这样的场景中实现它。调用外部函数对于根据点击的pieslice动态更改数据提供者标记至关重要。请注意,在javascript函数中我可以调用console.log()(只是不在其作用域之外的函数)。

以下是浏览器控制台上显示的错误:

zone.js:169 Uncaught TypeError: Cannot read property 'Call' of undefined
    at breakdown-chart.component.ts:51
    at b.a.inherits.b.fire (amcharts.js:3)
    at b.clickSlice (pie.js:10)
    at SVGGElement.<anonymous> (pie.js:5)
    at SVGGElement.wrapFn [as __zone_symbol___onmouseup] (zone.js:1199)
    at ZoneDelegate.webpackJsonp.695.ZoneDelegate.invokeTask (zone.js:398)
    at Zone.webpackJsonp.695.Zone.runTask (zone.js:165)
    at SVGGElement.ZoneTask.invoke (zone.js:460)

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以将this设置为变量,然后稍后再参考。

import { AmChartsService } from "@amcharts/amcharts3-angular";

@Component({
  template: `<div id="chartdiv" [style.width.%]="100" [style.height.px]="500"></div>`
})
export class AppComponent {
  private chart: any;

  constructor(private AmCharts: AmChartsService) {}

  public whatever(){}

  ngOnInit() {
    // Set this to that
    let that = this;

    this.chart = this.AmCharts.makeChart("chartdiv", {
      "type": "pie",
      "theme": "light",
      "dataProvider": [],
      "listeners": [{
            event: 'clickSlice',
            method: function(event) {
                // Use that to refer to this
                that.whatever();
            }
        }],
      ...
    });
  }
}