nathannewyen
nathannewyen

Reputation: 253

How can I put API data to angular chart?

I'm trying to put spotify API to a chart and here is my components for chart:

API from spotify:

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

Chart example:

  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" },
  ];

enter image description here

Upvotes: 1

Views: 382

Answers (1)

Mahipal Choudhary
Mahipal Choudhary

Reputation: 405

You can use this example

Data must be in the following format...

  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' }
  ];

Updated answer:

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
}

Live example Demo

I hope it is helpful for you. :)

Upvotes: 2

Related Questions