2017-05-31 126 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(); 
      } 
     }], 
     ... 
    }); 
    } 
}