Voici ma base de code
export class myComponent implements OnInit { minHist; maxHist; } public callAmcharts(whichFilterType:String){ this.amchart = AmCharts.makeChart( "chart", { "type": "serial", "theme": "light", "dataProvider": this.TrendData, "valueAxes": [ { "gridColor": "#FFFFFF", "gridAlpha": 0.2, "dashLength": 0 }], "gridAboveGraphs": true, "startDuration": 1, "graphs": [ { "balloonText": "[[category]]: <b>[[value]]</b>", "fillAlphas": 0.8, "lineAlpha": 0.2, "type": "column", "valueField": "dCount", "showHandOnHover":true } ], "chartCursor": { "categoryBalloonEnabled": false, "cursorAlpha": 0, "zoomable": false }, "categoryField": "dRange", "categoryAxis": { "gridPosition": "start", "gridAlpha": 0, "tickPosition": "start", "tickLength": 20, "labelRotation": 45 }, "export": { "enabled": true } }); this.amchart.addListener("clickGraphItem",this.myfunc);
}
Maintenant, l'événement onclick myfunc
est appelé. Mais étrangement, je ne peux pas accéder à aucune variable globale là-bas en utilisant this
. Si c'est un problème de scope
, il devrait donner une erreur en appelant myfunc
aussi correctement?
public myfunc(e:any){ var range= e.item.category; let range_arr = range.split("-"); this.minHist=range_arr[0]; this.maxHist=range_arr[1]; }
Je reçois une erreur en indiquant Uncaught TypeError: Cannot set property 'minHist' of undefined
Changement
this.amchart.addListener("clickGraphItem",this.myfunc);
à
this.amchart.addListener("clickGraphItem",this.myfunc.bind(this));
Selon vos entrées, cela fonctionnera également:
this.amchart.addListener("clickGraphItem",(e)=> this.myfunc(e));
Qui est la version plus courte de:
this.amchart.addListener("clickGraphItem",(e)=> { return this.myfunc(e); });
Lecture suggérée: Comment accéder au contexte correct de `this` dans un rappel?