Chartjs-Chart.js doesn't read input data coming from observable (Angular)

0๐Ÿ‘

[SOLVED]

The problem was that the data arrived in an async way and was not yet ready when the component was created. Hence, I had to wrap the new Chart logic into an observable and then used switchMap to take advantage of its higher-order ability.

ngAfterViewInit() {
    this.setChart().subscribe();
  }

  setChart() {
    return this.soldUnitsPerMonth.pipe(
      switchMap((items) => {
        return this.defineChartDetails(items);
      })
    );
  }

  defineChartDetails(items: any) {
    return new Observable((obs) => {
      if (this.chart) {
        this.chart.destroy();
      }

      this.chart = new Chart(this.chartRef.nativeElement, {
        type: 'bar',
        data: {
          labels: items.map((item: any) => item.month + 1),
          datasets: [
            {
              label: 'Interesting Data',
              data: items.map((item: any) => item.totalSalesInMonth),
            },
          ],
        },
      });
    });
  }

If anyone runs into this problem, please note that you also have to unsubscribe from the setChart method using ngOnDestroy.

Leave a comment