【发布时间】:2019-12-10 16:38:24
【问题描述】:
我想这是一个与 javascript 闭包相关的一般问题,但我将使用具体的示例,因为我无法以角度思考问题。
我有一个角度组件,它使用 Highcharts 库来显示图表。当用户通过鼠标拖动选择图表的一部分时,Highcharts 可以发出事件。该事件提供了一个回调函数,它接受 2 个参数,例如-function(chartRef, event)。我已经为回调函数提供了一个类方法的引用。当事件由 highcharts 发出时,方法内部this 绑定到chartRef(回调函数范围)而不是角度组件类(AppComponent)本身。如何获取角度组件类,以便我可以将事件返回的值用于我的角度应用程序?
import { Chart } from 'angular-highcharts'
export class AppComponent {
@Output() selection = new EventEmitter<any>()
chart: Chart;
ngOnInit() {
this.init();
}
init() {
let chart = new Chart({
chart: {
zoomType: 'x',
events: {
selection: this.onChartSelectionEvent,
},
},
// code removed for brevity
this.chart = chart
)
}
onChartSelectionEvent(chartRef, event) {
console.log(chartRef.xAxis[0].min) // logs correctly
console.log(chartRef.xAxis[0].max) // logs correctly
this.selection.next(chartRef.xAxis[0].max) // doesn't work
// ERROR Error: Cannot read property 'next' of undefined
// because `this` refers to the chartRef, not the angular class
}
}
【问题讨论】:
标签: javascript angular typescript highcharts