繁体   English   中英

如何从 API 正确使用 ng2 图表和 Angular 显示数据

[英]How can I show data using ng2 charts and Angular correctly from an API

你好,请问可以帮我吗? 我正在尝试在 Angular 应用程序中使用 ng2 图表显示数据,我正在使用 Firebase 从 API 获取数据,但它不起作用,我不知道我做错了什么。

我得到的数据是这样的:

{
    "2017": {
        "bebes": 67,
        "hombres": 20,
        "mujeres": 30
    },
    "2018": {
        "bebes": 33,
        "hombres": 10,
        "mujeres": 49
    },
    "2019": {
        "bebes": 45,
        "hombres": 20,
        "mujeres": 34
   }

(这太糟糕了,我知道)。

我创建了一个服务来仅使用一种方法来获取数据。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class VentasService {

  private url = 'https://dbb-fa0a5.firebaseio.com/data.json';

  constructor(private http: HttpClient) {
  }

  getVentas() {
    return this.http.get(this.url);
  }
}
}

这是带有图形栏的组件。

import { Component } from '@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';   
import { VentasService  } from '../../../../services/ventas.service';

@Component({
  selector: 'app-bar-grafic',
  templateUrl: './bar-grafic.component.html',
  styles: []
})
export class BarGraficComponent {
  year_2017: any = []
  year_2018: any = []
  year_2019: any = []

  constructor(private ventas : VentasService){

  this.ventas.getVentas().subscribe( (data : any) =>{
    this.year_2017 = data['2017']
    this.year_2018 = data['2018']
    this.year_2019 = data['2019']
    // testing
    console.log(this.year_2017.mujeres);
  })



  }

  public barChartOptions: ChartOptions = {
    responsive: true,
    // We use these empty structures as placeholders for dynamic theming.
    scales: { xAxes: [{}], yAxes: [{}] },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'end',
      }
    }
  };

  public barChartLabels: Label[] = ['2017', '2018', '2019'];
  public barChartType: ChartType = 'bar';
  public barChartLegend = true;


  public barChartData: ChartDataSets[] = [
    { data: [this.year_2019.mujeres, this.year_2018.mujeres, this.year_2017.mujeres], label: 'Mujeres' },
    { data: [this.year_2019.hombres, this.year_2018.hombres, this.year_2017.hombres], label: 'Hombres' },
    { data: [this.year_2019.bebes, this.year_2018.bebes, this.year_2017.bebes], label: 'Bebes' }
  ];

  public refresh(): void {
    this.ventas.getVentas().subscribe( (data : any) =>{
      this.year_2017 = data['2017']
      this.year_2018 = data['2018']
      this.year_2019 = data['2019']
      console.log(this.year_2017.mujeres);

    })
  }
}

如果我尝试在控制台中打印它,一切看起来都很好,但图形不显示数据

在此处输入图片说明

我真的不知道为什么:(

我检查了您的代码,发现问题在于您在数据从服务到达之前将数据分配给barChartData 由于您的服务正在执行异步操作,因此您需要在订阅块内移动分配数据的代码。

就像您的服务是一项异步任务一样,我正在使用timer运算符来添加异步行为。

请在下面找到代码:

import { Component, OnInit } from "@angular/core";
import { ChartOptions, ChartType, ChartDataSets } from "chart.js";
import { Label } from "ng2-charts";
import { timer } from "rxjs";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  year_2017: any = [];
  year_2018: any = [];
  year_2019: any = [];

  public barChartData: ChartDataSets[] = [];

  constructor() {
    timer(1000).subscribe((data: any) => {
      this.year_2017 = { mujeres: 10, hombres: 20, bebes: 30 };
      this.year_2018 = { mujeres: 5, hombres: 10, bebes: 15 };
      this.year_2019 = { mujeres: 2, hombres: 4, bebes: 6 };
      // testing
      console.log(this.year_2017.mujeres);

      this.barChartData = [
        {
          data: [
            this.year_2019.mujeres,
            this.year_2018.mujeres,
            this.year_2017.mujeres
          ],
          label: "Mujeres"
        },
        {
          data: [
            this.year_2019.hombres,
            this.year_2018.hombres,
            this.year_2017.hombres
          ],
          label: "Hombres"
        },
        {
          data: [
            this.year_2019.bebes,
            this.year_2018.bebes,
            this.year_2017.bebes
          ],
          label: "Bebes"
        }
      ];
    });
  }

  public barChartOptions: ChartOptions = {
    responsive: true,
    // We use these empty structures as placeholders for dynamic theming.
    scales: { xAxes: [{}], yAxes: [{}] },
    plugins: {
      datalabels: {
        anchor: "end",
        align: "end"
      }
    }
  };

  public barChartLabels: Label[] = ["2017", "2018", "2019"];
  public barChartType: ChartType = "bar";
  public barChartLegend = true;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM