Chartjs-Angular chartjs not showing data properly

0👍

I just found out what I was doing wrong: I’m using axios, which is promise-based, so taking @JeffFhol’s suggestion into account, my two instances were blank since I was initializing the chart at the same time I was making the API request.

The solution was to initialize the chart in the then clause of the axios request, which ensures that my instances aren’t empty.

Here’s the snippet that worked:

axios({
  method: 'post',
  url: 'url_to_api',
  headers: {
    'Content-Type' : 'application/json'
     // custom data headers, etc.
  },
  data: {
    // data to be sent
  }
})
.then(response => {
  this.weight_dates = response.data.weight_date;
  this.weight_data = response.data.weight_data;

  //   code for chart here
})
.catch(error => {
  console.log(error)
})

0👍

It looks like you want to subscribe to an observable which can provide the data, and once it comes in, you can then initialize your chart. Usually, we would want to have the HTTP call occur within a service, but to simplify, this is how we could do with within a component:

import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Component, OnInit} from '@angular/core';


export class MyChart implements OnInit {

  constructor(private http: HttpClient) { }

  private getData() {
    let url = '[SOME-URL]' // your path to the data API endpoint
    return this.http.get(url) as Observable<Array<any>>; // you would want to use correct typings here, instead of <any>
  }

  ngOnInit() {
    this.getData().subscribe((data: any) => {
      console.log(data);
      // assign your data here, and then initialize your chart.
    });
  }
}

Leave a comment