2017-05-31 78 views
1

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

我的问题是在这里:

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) 

谢谢!

+0

确实,我们正试图达到类似的目的。这很奇怪,我之前无法找到那篇文章。 –

+0

它实际上是关于javascript(Closure函数失去'this'绑定)的最常见问题之一, –

回答

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(); 
      } 
     }], 
     ... 
    }); 
    } 
}