Search code examples
jsonangularchartshttpclienthttp-get

Creating a dynamic chart in angular using json data


I am a beginner and I try to create a dynamic pie chart using angular and Kendo UI. I want to get data from json file and it is located inside the assets folder. I tried to link the .ts file and json file. but the chart does not show.

This is my component.html file

<kendo-chart [transitions]="false"  [style.height]="'100%'" [style.width]="'100%'">
  <kendo-chart-series>
    <kendo-chart-series-item type="pie"
                             [data]="data"
                             categoryField="kind"
                             field="share"
                             [autoFit]="true"
                             *ngIf="data">
      <kendo-chart-series-item-labels [align]="labelAlign"
                                      color="#000"
                                      [content]="labelContent">
      </kendo-chart-series-item-labels>
    </kendo-chart-series-item>
  </kendo-chart-series>
  <kendo-chart-legend [visible]="false"></kendo-chart-legend>
</kendo-chart>

This is my db.json file

{"data": [
    {
      "id": 1,
      "kind": "Solar",
      "share": 5
    },
    {
      "id": 2,
      "kind": "Wind",
      "share": 2
    },
    {
      "id": 3,
      "kind": "Geothermal",
      "share": 1
    },
    {
      "id": 4,
      "kind": "Natural Gas",
      "share": 1
    },
    {
      "id": 5,
      "kind": "Coal",
      "share": 80
    },
    {
      "id": 6,
      "kind": "Hydroelectric",
      "share": 2
    },
    {
      "id": 7,
      "kind": "Nuclear",
      "share": 2
    },
    {
      "id": 8,
      "kind": "Other",
      "share": 1
    }
  ]
}

This is my component.ts file

  data = null;
  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('assets/db.json').subscribe(
      data => this.data = data,
      err => console.error('File is missing: ', err),
    );
  }

  public labelContent(e: any): string {
    return e.category;
  }
}

Solution

  • Try to modify the data you pass into <kendo-chart-series-item> tag to be like that [data]="data?.data", as [data] should be in the form of an array of objects, and your array of objects is the value of the key data in your json file.