Kévin
Kévin

Reputation: 557

ngx-echarts update data from API

I encouter problem for updating the data of my ngx-echarts (Angular 10) ngx-echarts : v6.0

I would like to fetch the data from my api and then update the value into the chart. Actually, it's working one time, and the other no.. It seems that it's depends on the speed of loading page. If it's fast, then the value is not updated ( but in console i see the value that should be inside the chart..)

I don't find any good doc for updating the chart. I hope someone now this and can correct me. thanks

import { delay } from 'rxjs/operators';
import { AfterViewInit, Component, ElementRef, Input, OnChanges, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { NbThemeService } from '@nebular/theme';
import { RestApiService } from '../../shared/rest-api/rest-api.service';
import { ActivatedRoute } from '@angular/router';
import { EChartOption } from 'echarts';
declare const echarts: any;

@Component({
  selector: 'ngx-solar',
  templateUrl: './solar.component.html',
  styleUrls: ['./solar.component.scss']
})
export class SolarComponent implements AfterViewInit, OnDestroy, OnInit {
  id: any;
  value: number = 10; //default value here

  option: any = {};
  themeSubscription: any;
  dynamicData: any;
 
  @Input('chartValue')
  set chartValue(value: number) {
    if (this.option.series) {
      this.option.series[0].data[0].value = value;
      this.option.series[0].data[1].value = 100 - value;
      this.option.series[1].data[0].value = value;
    }
  }
    
  
  ngOnInit(): void{

    this.route.params.subscribe(params => {
      this.id = params['id'];
    });
    


    this.dataService.getMetricsOfContainer(this.id).subscribe((res)=>{
      console.log(JSON.stringify(res.cpu)); //value appears here all time
        this.value = res.cpu;
        // var myChart = echarts.init(document.getElementById('chart')); 
        // myChart.setOption(this.option);
    }); 
    
    
  }

  constructor(private theme: NbThemeService, private dataService: RestApiService, private route: ActivatedRoute) {
  }


  ngAfterViewInit() {
    this.themeSubscription = this.theme.getJsTheme().pipe(delay(1)).subscribe(config => {

      const solarTheme: any = config.variables.solar;

      this.option = Object.assign({}, {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)',
        },
        series: [
          {
            name: ' ',
            clockWise: true,
            hoverAnimation: false,
            type: 'pie',
            center: ['45%', '50%'],
            radius: solarTheme.radius,
            data: [
              {
                value: this.value,
                name: ' ',
                label: {
                  normal: {
                    position: 'center',
                    formatter: '{d}%',
                    textStyle: {
                      fontSize: '22',
                      fontFamily: config.variables.fontSecondary,
                      fontWeight: '600',
                      color: config.variables.fgHeading,
                    },
                  },
                },
                tooltip: {
                  show: false,
                },
                itemStyle: {
                  normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      {
                        offset: 0,
                        color: solarTheme.gradientLeft,
                      },
                      {
                        offset: 1,
                        color: solarTheme.gradientRight,
                      },
                    ]),
                    shadowColor: solarTheme.shadowColor,
                    shadowBlur: 0,
                    shadowOffsetX: 0,
                    shadowOffsetY: 3,
                  },
                },
                hoverAnimation: false,
              },
              {
                value: 100 - this.value,
                name: ' ',
                tooltip: {
                  show: false,
                },
                label: {
                  normal: {
                    position: 'inner',
                  },
                },
                itemStyle: {
                  normal: {
                    color: solarTheme.secondSeriesFill,
                  },
                },
              },
            ],
          },
          {
            name: ' ',
            clockWise: true,
            hoverAnimation: false,
            type: 'pie',
            center: ['45%', '50%'],
            radius: solarTheme.radius,
            data: [
              {
                value: this.value,
                name: ' ',
                label: {
                  normal: {
                    position: 'inner',
                    show: false,
                  },
                },
                tooltip: {
                  show: false,
                },
                itemStyle: {
                  normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      {
                        offset: 0,
                        color: solarTheme.gradientLeft,
                      },
                      {
                        offset: 1,
                        color: solarTheme.gradientRight,
                      },
                    ]),
                    shadowColor: solarTheme.shadowColor,
                    shadowBlur: 7,
                  },
                },
                hoverAnimation: false,
              },
              {
                value: 28,
                name: ' ',
                tooltip: {
                  show: false,
                },
                label: {
                  normal: {
                    position: 'inner',
                  },
                },
                itemStyle: {
                  normal: {
                    color: 'none',
                  },
                },
              },
            ],
          },
        ],
      });
    });
  }

  ngOnDestroy() {
    this.themeSubscription.unsubscribe();
  }
}


Html:

<nb-card size="tiny" class="solar-card">
    <nb-card-header>Solar Energy Consumption</nb-card-header>
    <nb-card-body>
      <div id="chart" echarts [options]="option" class="echart">
      </div>
      <div class="info">
        <div class="h4 value">6.421 kWh</div>
        <div class="details subtitle-2"><span>out of</span> 8.421 kWh</div>
      </div>
    </nb-card-body>
  </nb-card>

Upvotes: 1

Views: 3508

Answers (1)

Asder999
Asder999

Reputation: 87

I had the same problem, more or less: I wanted to populate the graph with data from api.

Instead of fetching only the data with @Input(), try to fetch the whole options object.

I solved creating the ngx-echart's options object in a service that takes the data I need to show, and give me back the options object, wich I can pass directly in the echart tags.

Probably I'm in late for your issue, but I hope this tips could help the next one. :)

Upvotes: 3

Related Questions