Meriem Bader
Meriem Bader

Reputation: 173

How to Pass data from api into pie chart with angular

I would like to pass the output of an API in a piechart canvas with angular but I could not achieve any result, the API is consumed but I have a problem associating it with the piechart (datapoints) the code just below.

app.component.ts

import { Component, OnInit } from '@angular/core';
import { EmailValidator } from '@angular/forms';
import { Router, NavigationEnd } from '@angular/router';
import { ApiService } from './api.service';
import { ApistatService } from './apistat.service';
import * as CanvasJS from './canvasjs.min';
//var CanvasJS = require('./canvasjs.min');
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  elements: any[];
  constructor(
    private apistatService: ApistatService
  ) {  
    this.elements = [];
  }
    ngOnInit() {
    let chart = new CanvasJS.Chart("chartContainer", {
        theme: "light2",
        animationEnabled: true,
        exportEnabled: true,
        title:{
            text: "Monthly Expense"
        },
        data: [{
            type: "pie",
            showInLegend: true,
            toolTipContent: "<b>{elements.total}</b>: ${y} (#status)",
            indexLabel: "{name} - #percent%",
            dataPoints: [
                
                { y: 120, name: "Insurance" },
                { y: 300, name: "Traveling" },
                { y: 800, name: "Housing" },
                { y: 150, name: "Education" },
                { y: 150, name: "Shopping"},
                { y: 250, name: "Others" }
            ]
        }]
  });   
  this.apistatService.getData().subscribe((data:any) => {
    if(data.status === 200) {
      console.log(data.response);
      this.elements = data.response;
    }
  })    
    chart.render();
    }
}

app.component.html

<div id="chartContainer"  style="height: 370px; width: 100%; margin-left:auto;margin-right:auto;">
  

  
</div>

enter image description here

Upvotes: 0

Views: 2229

Answers (1)

Pritesh
Pritesh

Reputation: 337

To consume API data in pie chart you should just set data from API to dataPoints array just make sure your API data has same formatting as currently available inside dataPoints array which you are passing in data array while rendering chart, and it will work.

Upvotes: 2

Related Questions