【问题标题】:How to get the angular component class reference inside an emitted Highcharts selection event callback function?如何在发出的 Highcharts 选择事件回调函数中获取角度组件类引用?
【发布时间】: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
  }
}

Stackblitz for the problem

【问题讨论】:

    标签: javascript angular typescript highcharts


    【解决方案1】:

    您可以使用IIFE 来存储组件引用:

    onChartSelectionEvent = (function(self) {
        console.log(self)
        return function(chartRef: any, chartEvent:any){
        console.log(chartRef.xAxis[0].min)
        console.log(chartRef.xAxis[0].max)
        console.log(self)
        }
        // `this` is bound to the chartRef that is emmited by the Highcharts event
        // How can I get a hold of the angular component class (AppComponent) instead?
        //this.selection.next(chartRef.xAxis[0].max)
    })(this)
    

    演示:https://stackblitz.com/edit/angular-kqzyjv?file=src/app/app.component.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多