簡體   English   中英

如何將 API 數據放入 angular 圖表?

[英]How can I put API data to angular chart?

我正在嘗試將 spotify API 放到圖表中,這是我的圖表組件:

來自Spotify的API:

ngOnInit() {
    this.route.params.pipe(map((params) => params["id"])).subscribe((id) => {
      this.userService.getAudioFeature(id).subscribe((trackFeature) => {
        this.trackFeature = trackFeature;
        console.log(this.trackFeature);
      });
    });
}

圖表示例:

  barChartOptions: ChartOptions = {
    responsive: true,
  };
  barChartLabels: Label[] = [
    "Apple",
    "Banana",
    "Kiwifruit",
    "Blueberry",
    "Orange",
    "Grapes",
  ];
  barChartType: ChartType = "bar";
  barChartLegend = true;
  barChartPlugins = [];

  barChartData: ChartDataSets[] = [
    { data: [this.trackFeature.danceability, 37, 60, 70, 46, 33], label: "Audio Features" },
  ];

在此處輸入圖像描述

你可以使用這個例子

數據必須采用以下格式...

  public barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
  public barChartType: ChartType = 'bar';
  public barChartLegend = true;
  public barChartPlugins = [pluginDataLabels];

  public barChartData: ChartDataSets[] = [
    { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
    { data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' }
  ];

更新的答案:

export class AppComponent  {
  trackFeature:any;

  public barChartOptions: ChartOptions = {
    responsive: true,
  };
  public barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
  public barChartType: ChartType = 'bar';
  public barChartLegend = true;
  public barChartPlugins = [];
  public barChartData: ChartDataSets[] = [
    { data: [10,20,30,40,50], label: 'Series A' }
  ];

   constructor() {}
  ngOnInit() {
    //push data from api
    this.route.params.pipe(map(params => params["id"])).subscribe(id => {
      this.userService.getAudioFeature(id).subscribe(trackFeature => {
        this.trackFeature = trackFeature;
        //if data received then push into your chart
        if (this.trackFeature != null) {
          this.barChartData = [
            {
              data: [this.trackFeature.danceability, this.trackFeature.energy],
              label: "Series A"
            }
          ];
        }
      });
    });

  } //end ngOnInit
}

現場示例演示

我希望它對你有幫助。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM