javascriptangulartypescriptangular12ng-apexcharts

how to bind the values from api in apex chart using angular 12


I want to bind the values from api in apexchart area chart

app.comp.ts

salesforpurchase : result[]
 this.service.sales().subscribe (data=> {
      this.salesforpurchase=data.data

In result[] , values will be

date:2012-03-02, sales:256

and so on...

 intializationChartoption():void {
    this.title ={
      text: 'linechart'
    };

  this.series = [{
         name: 'Purchase',
         data: [20,10,300] //static data . Here i want to bring sales value from result[]
       }]
     
      

    this.chart ={
      type: 'area',
      width :650,
      
    };
  }

html

<apx-chart [series]="series" [chart]="chart" [title]="title"
></apx-chart>

Please help me how to bind the data dynamically to apex chart


Solution

  • First thing to notice is to initialize the value within the subscription callback. In other words, you'd need to subscribe to the observable where it's response is required.

    Second, to get only the sales property of each object of the array as it's own array, you could use the Array#map function.

    Try the following

    ngOnInit() {
      this.service.sales().subscribe(
        (data: any) => {
          this.intializationChartoption(  // <-- this call *must* be inside the subscription callback
            data.map((item: any) => item.sales)
          );
        },
        error => {
          // handle errors
        }
      );
    }
    
    intializationChartoption(series: number[]): void {
      this.title ={
        text: 'linechart'
      };
    
      this.series = [{
        name: 'Purchase',
        data: series
      }];
    
      this.chart = {
        type: 'area',
        width :650,
        };
      }
    }