Chart.js.json文件中数据的Angular 误差

r8xiu3jd  于 2023-03-18  发布在  Chart.js
关注(0)|答案(2)|浏览(128)

我有一个简单的数据数组,我想使用chart.js库在图表中显示它。唯一的错误似乎是一些DeepPartialObject引用了图表选项中的一些问题(y轴和x轴)。我是Angular和Chart.js的新手,一直在努力解决这个问题。
我当前的代码如下所示:

import { Chart } from 'chart.js/auto';
import { Component, OnInit } from '@angular/core';
import { Fruit } from './fruit.model';
import { FruitService } from './fruit.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    title = 'angular-fetch-json-data';
    public fruits: Fruit[];
    public chart: any;

    public constructor(private fruitService: FruitService) { }

    public ngOnInit(): void {
        this.fruitService.getFruits().subscribe((response) => {
            this.fruits = response.fruits;
            this.createChart();
        })
    }

    createChart() {
        if (this.chart) {
            this.chart.destroy();
        }

        // Extract the labels and data from the fruits array
        const labels = this.fruits.map((fruit: any) => fruit.fruit);
        const data = this.fruits.map((fruit: any) => fruit.amountBought);

        this.chart = new Chart('canvas', {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        data: data,
                        borderColor: '#3cba9f',
                        fill: false
                    },
                    {
                        data: data,
                        borderColor: '#ffcc00',
                        fill: false
                    },
                ]
            },
            options: {
                legend: {
                    display: false
                },
                scales: {
                    xAxes: [{
                        display: true
                    }],
                    yAxes: [{
                        display: true,
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
    }
}
data.json file:

   

     {
        "fruits": [
            {
                "fruit": "Apple",
                "size": "Large",
                "color": "Red",
                "amountBought": 100
            },
        
            {
                "fruit": "Banana",
                "size": "Small",
                "color": "Yellow",
                "amountBought": 76
            },
            {
                "fruit": "Strawberry",
                "size": "Medium",
                "color": "Red",
                "amountBought": 732
            },
            {
                "fruit": "Blueberry",
                "size": "Small",
                "color": "Blue",
                "amountBought": 27
            }
        ]
        }

The issues are with Yaxes and xAxes, at least according to the compiler. I've tried numerous things with those, and also changing different stuff with the chart options, but can't seem to figure it out.
qeeaahzv

qeeaahzv1#

问题1

正如@Stefan提到的,由于可观察对象是异步的,因此在subscribe()回调中移动this.createChart()。通过移动到回调中,将保证this.createChart()在返回可观察对象时执行。

this.fruitService.getFruits().subscribe((response) => {
  this.fruits = response.fruits;

  this.createChart();
});

问题2

我认为您安装的 chart.js 版本为3或更高版本,这与您当前的Chart.js配置不兼容。根据文档,不再支持xAxes和yAxes。请按照迁移说明进行操作:

  • 删除了xAxesyAxes阵列,轴选项现在是按比例ID键控的单独比例
  • legendtitletooltip命名空间已从options移动到options.plugins

要从组件呈现图表(回写代码),您应该使用@ViewChild装饰器。
您的代码应该如下所示:
组件

import { ElementRef, ViewChild } from '@angular/core';
import { ChartOptions } from 'chart.js';

@ViewChild('baseChart', { static: true })
  canvasElem: ElementRef<HTMLCanvasElement>;

  createChart() {
    if (this.chart) {
      this.chart.destroy();
    }

    // Extract the labels and data from the fruits array
    const labels = this.fruits.map((fruit: any) => fruit.fruit);
    const data = this.fruits.map((fruit: any) => fruit.amountBought);

    const ctx = this.chart.nativeElement.getContext('2d');
    this.chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [
          {
            data: data,
            borderColor: '#3cba9f',
            fill: false,
          },
          {
            data: data,
            borderColor: '#ffcc00',
            fill: false,
          },
        ],
      },

      options: {
        plugins: {
          legend: {
            display: false,
          },
        },
        scales: {
          x: {
            display: true,
          },

          y: {
            display: true,
            ticks: {
              beginAtZero: true,
            },
          },
        },
      } as ChartOptions<'line'>,
    });
  }

超文本标记语言

<canvas #baseChart class="chart"></canvas>

Demo @ StackBlitz

rryofs0p

rryofs0p2#

在你们的帮助下我完成了代码!非常感谢!下面是工作代码:

import { Chart } from 'chart.js/auto';

import { Component, OnInit } from '@angular/core';

import { Fruit } from './fruit.model';
import { FruitService } from './fruit.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'angular-fetch-json-data';
  public fruits: Fruit[];
  public chart: any;

  public constructor(private fruitService: FruitService){
  }

  public ngOnInit(): void {
    this.fruitService.getFruits().subscribe((response) => {
      this.fruits = response.fruits;
      this.createChart();
    })
  }

  createChart() {
    if (this.chart) {
      this.chart.destroy();
    }

    // Extract the labels and data from the fruits array
    const labels = this.fruits.map((fruit: any) => fruit.fruit);
    const data = this.fruits.map((fruit: any) => fruit.amountBought);

    
    this.chart = new Chart('canvas', {
      type: 'line', 
      data: {
        labels: labels,
        datasets: [
          {
            data: data,
            borderColor: '#3cba9f', 
            fill: false 
          },
        ]
      },
      options: {
        scales: {
          xAxes: {
            display: true
          },
          yAxes: {
            display: true,
              beginAtZero: true
            
          }
        }
      }
    });
  }
}

相关问题