Tolgon
Tolgon

Reputation: 33

Using a prepared dataset in chart.js

I can't seem to figure out how to get my charts to work. I've prepared the data, but everytime I add the labels for example (labelDate) it just gives me an undefined variable when I log it.

    ngOnInit(): void {
    let labelDate;
    this._estimateService.getEstimates()
        .subscribe(estimateData => {
            const key = 'data';
            const groupedEstimates = groupBy(estimateData[key], 'estimate_date');
            // console.log(groupedEstimateData);

            const groupedEstimatesFiltered = omit(groupedEstimates, 'null');

            Object.entries(groupedEstimatesFiltered)
                .map(([date, estimatedData]) => {
                    labelDate = moment(date).format('DD MMM');   // Change it here
                    console.log(labelDate, estimatedData.length + ' - this is the first log');
                });
        });


    if (!this.data) {
        const color = Chart.helpers.color;
        this.data = {
            labels: [labelDate], // Doesnt work - logs as undefined
            datasets: [
                {
                    data: [estimateData.length] // Same as above
                },

What the dataset log looks like:

Upvotes: 0

Views: 62

Answers (1)

MAQs17
MAQs17

Reputation: 26

Your if block probably executes before your subscription's next finishes. To avoid this you could call observable's toPromise to change it into a promise and await it or move the if block to the bottom of subscription's next so you make sure you don't have a race there.

Upvotes: 1

Related Questions