在角度中解构 chartjs 的对象

问题描述 投票:0回答:1

我正在尝试将 chart.js 添加到我的 angular 14 项目中,但遇到了配置对象的问题:我正在使用 new Chart(#tagName, config),如果配置是函数内的单个对象,则一切正常很好,但是如果我将配置分离到不同的对象(为了更好的可读性),它会抛出类型不匹配错误。我做错了什么?

我的代码:

export class ChartComponent implements OnInit, OnChanges {
  public chart: any;
  @Input() chartType: ChartConfiguration["type"] = "line";
  @Input() chartDataSets?;
  @Input() chartDataLables?;
  @Input() chartOptions?;
  @Output() zoomComplete = new EventEmitter();

  constructor() {}

  // DEFAULTS OPTIONS
  private chartDefaultOptions = {
    elements: {
      line: {
        tension: 0.5,
      },
    },
    scales: {
      y: {
        position: "left",
        stacked: true,
      },
      x: {
        stacked: true,
        // type: 'time',
      },
    },
    plugins: {
      // zoom: this.zoomOptions,
    },
  };

  // PLUGINS

  private zoomOptions = {
    zoom: {
      mode: "x",
      drag: {
        enabled: true,
        // drawTime: 'afterDraw',
      },
    },
    // limits: {
    //   x: { min: 'original', max: 'original', minRange: 1000 * 60 * 10, },
    // },
  };

  
  // CORE ATTRIBUTES
  private chartConfig = {
    type: this.chartType,
    data: {
      datasets: this.chartDataSets,
      labels: this.chartDataLables,
    },
    options: this.chartDefaultOptions,
  };

  ngOnInit(): void {}

  ngOnChanges(changes: SimpleChanges): void {
    const chartExist = Chart.getChart("serverChart");
    if (chartExist !== undefined) chartExist.destroy();

    Chart.register(...registerables, zoomPlugin);
    this.createChart();
  }

  createChart() {
    this.chart = new Chart("serverChart", this.chartConfig); // <- HERE BE ERRORS
  }

  // CHART OPTIONS

  combineOptions() {
    return {
      ...this.chartDefaultOptions,
      ...this.chartOptions,
    };
  }

  

  // EVENTS

  public chartClicked({ event, active }: { event?: ChartEvent; active?: {}[]; }): void {
    console.info(event, active);
  }

  public chartHovered({ event, active }: { event?: ChartEvent; active?: {}[]; }): void {
    console.info(event, active);
  }
}

我希望能够添加选项作为道具,并将它们与元素的一些默认选项结合起来,使图表组件更通用,所以如果有更好的方法,我会很乐意学习。

角度.v14.2.0;图表.js v.4.2.0; 谢谢。

angular chart.js
1个回答
0
投票

尝试调用

plugins: this.zoomOptions
或从缩放选项中删除包装
zoom
,否则缩放路径将是
plugins.zoom.zoom
这就是您的类型不匹配的原因。

// PLUGINS
zoomOptions = {
  zoom: {
    mode: "x",
    drag: {
      enabled: true,
    },
  },
};

// DEFAULTS OPTIONS
chartDefaultOptions = {
  elements: {
    line: {
      tension: 0.5,
    },
  },
  scales: {
    y: {
      position: "left",
      stacked: true,
    },
    x: {
      stacked: true,
    },
  },
  plugins: this.zoomOptions,
};

// CORE ATTRIBUTES
chartConfig = {
  type: this.chartType,
  data: {
    datasets: this.chartDataSets,
    labels: this.chartDataLables,
  },
  options: this.chartDefaultOptions,
};

console.log("options.plugins", this.chartConfig.options.plugins);

© www.soinside.com 2019 - 2024. All rights reserved.