0

I'm trying to load chartist data via api call, though the data is returned but does not load in chartist series.

// Initialize data series
seriesData: any[] = [];

// Function to retrieve data from api
getSeriesData() {
    this.uid.getSeriesData(this.auth.getCurrentUser()).then(
      data => this.seriesData = data, // This is populated
      err => console.log(err)
    );
  }

//ngInit
ngOnInit() {
   this.getSeriesData();

// Chartist
const dataDailySalesChart: any = {
      labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
      series: [
        this.seriesData // THIS IS ALWAYS EMPTY
      ]
    };
}
demo.b
  • 3,299
  • 2
  • 29
  • 29
  • Of course it's empty, you build the chart data before the promise could possibly have been resolved. Do it inside the callback, where you do have that data. – jonrsharpe Oct 19 '17 at 09:35
  • @jonrsharpe, Please can you help with an example. i'm new to this. – demo.b Oct 19 '17 at 10:59
  • Possible duplicate of [How to return data from promise](https://stackoverflow.com/questions/37533929/how-to-return-data-from-promise) – jonrsharpe Oct 19 '17 at 11:00
  • And various others. Read up on promises (or observables, which is what Angular uses natively - if you don't already know how to use promises, you might as well go directly to using observables). – jonrsharpe Oct 19 '17 at 11:01

1 Answers1

1

you are trying to build the chart data before the promise is resolved.Since getSeriesData is asynchronous, you should do somehting like this,

getSeriesData() {
    this.uid.getSeriesData(this.auth.getCurrentUser()).then(
      data => this.seriesData = data, // This is populated
      this.generateChart(this.seriesData),
      err => console.log(err)
    );
  }

ngOnInit() {
   this.getSeriesData();    
}

generateChart(chartData:any){
      const dataDailySalesChart: any = {
      labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
      series: [
       chartData
      ]
    };
};
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Thanks for the prompt response. Your example works, but i still cannot pass dataDailySalesChart to this variable because it's inside generateChart. var dailySalesChart = new Chartist.Line('#dailySalesChart', dataDailySalesChart, optionsDailySalesChart); – demo.b Oct 19 '17 at 10:57
  • you can just assign the data – Sajeetharan Oct 19 '17 at 11:00
  • You are great! Thank you so much. @jonrsharpe, i appreciate your contribution. – demo.b Oct 19 '17 at 11:41