如何实现折线图.js的自定义数据集数据结构?

amrnrhlw  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(200)

* 如何在不破坏index.esm.d.ts文件的情况下实现下面提到的数据集的自定义属性数据结构?*

我想在折线图中实现一个类似于这里的自定义数据集数据结构。我在Angular中使用ng2-charts来实现。

相关库版本:
  1. "@angular/core": "^14.2.0"
  2. "@types/chart.js": "^2.9.37"
  3. "chart.js": "^3.9.1"
  4. "ng2-charts": "^4.0.1"
  5. "typescript": "~4.7.2"
  6. "tslib": "^2.3.0",
下面是我想要实现的数据集数据结构的简化版本:
  1. data: [
  2. {id: '1', nested: {value: 500, extra: 'one'}},
  3. {id: '2', nested: {value: 1500, extra: 'two'}},
  4. ],

不幸的是,我在实现时遇到了以下打字错误:error TS2322: Type '{ id: string; nested: { value: number; extra: string; }; }' is not assignable to type 'number | ScatterDataPoint | BubbleDataPoint | null'.

如果我使用CustomDataPoint修改index.esm.d.ts文件:
  1. export interface CustomDataPoint {
  2. id: string,
  3. nested: {
  4. value: number,
  5. extra: string
  6. }
  7. }
  8. export interface ChartTypeRegistry {
  9. ...
  10. line: {
  11. chartOptions: LineControllerChartOptions;
  12. datasetOptions: LineControllerDatasetOptions & FillerControllerDatasetOptions;
  13. defaultDataPoint: CustomDataPoint | ScatterDataPoint | number | null; //### modified
  14. // defaultDataPoint: ScatterDataPoint | number | null; //### original
  15. metaExtensions: {};
  16. parsedDataType: CartesianParsedData;
  17. scales: keyof CartesianScaleTypeRegistry;
  18. };
  19. ...
  20. }

我不再得到打字错误。耶!P)的

* 如何在不破坏index.esm.d.ts文件的情况下实现上述数据集的自定义属性数据结构?*

这里是一个最小的代码集来重现这个...

折线图.组件.ts:
  1. import { Component, OnInit } from '@angular/core';
  2. import {ChartConfiguration, ChartType} from "chart.js";
  3. @Component({
  4. selector: 'app-chart-one',
  5. templateUrl: './chart-one.component.html',
  6. styleUrls: ['./chart-one.component.css']
  7. })
  8. export class ChartOneComponent implements OnInit {
  9. public chartData: ChartConfiguration['data'] = {
  10. datasets: []
  11. };
  12. public chartOptions: ChartConfiguration['options'];
  13. public chartType: ChartType = 'line';
  14. constructor() {}
  15. ngOnInit(): void {
  16. this.chartData.datasets = [
  17. {
  18. data: [
  19. {id: '1', nested: {value: 500, extra: 'one'}}, //TS Error here
  20. {id: '2', nested: {value: 1500, extra: 'two'}}, //TS Error here
  21. ],
  22. label: 'set 1',
  23. borderColor: '#3cba9f',
  24. fill: false,
  25. }
  26. ]
  27. this.chartOptions = {
  28. responsive: true,
  29. parsing: {
  30. xAxisKey: 'id',
  31. yAxisKey: 'nested.value'
  32. },
  33. };
  34. }
  35. }
线条图.组件.html:
  1. <div style="display: block">
  2. <canvas baseChart
  3. [data]="chartData"
  4. [options]="chartOptions"
  5. [type]="chartType">
  6. </canvas>
  7. </div>
xytpbqjk

xytpbqjk1#

如本文文档所述,您可以传递自己的自定义数据类型:

  1. import {ChartData} from 'chart.js';
  2. const datasets: ChartData<'bar', {key: string, value: number} []> = {
  3. datasets: [{
  4. data: [{key: 'Sales', value: 20}, {key: 'Revenue', value: 10}],
  5. parsing: {
  6. xAxisKey: 'key',
  7. yAxisKey: 'value'
  8. }
  9. }],
  10. };

相关问题