Updating data in ngx-echarts using API requests

Having trouble updating the data in my ngx-echarts (Angular 10) ngx-echarts : v6.0

I want to retrieve data from my API and then update the chart with the values. It seems to work sometimes, but not always. The issue seems to be related to the loading speed of the page. When it's fast, the value is not updated (even though I see the correct value in the console).

I couldn't find a good documentation on how to update the chart. Hoping someone can help me out. 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>

Answer №1

Dealing with a similar issue, I encountered the need to populate a graph with data from an API.

Rather than relying solely on fetching data with @Input(), consider retrieving the entire options object.

To resolve this, I created the ngx-echart's options object in a service that retrieves the necessary data and returns the options object for direct use in the echart tags.

Although it may be too late to assist you with your specific problem, I hope these insights prove helpful for future challenges. :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify that the password is entered correctly in Angular2

My Angular2 form looks like this: this.registerForm = formBuilder.group({ 'name': ['', Validators.required], 'email': ['', Validators.compose([Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+&bso ...

How to manually set the value of a select object in Angular 5

I am facing an issue with setting an object value manually for a select element. I have attempted to use setValue or patchValue with Object, but unfortunately, it did not yield the desired result. <mat-select placeholder="Selecione a resposta" (change) ...

Ways to categorize items retrieved from an HTTP request to the backend in Angular

When making a call to the backend using this http request: this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/)).subscribe(values => { this.studentObject = values; }); The studentObject is structured as shown below: { recor ...

Having trouble extracting value from another component or dealing with an architectural issue?

Just recently delving into Angular, I embarked on this journey last week with a small programming foundation. My current project involves creating a simple blog application where I need to pass a value from the root (app.component.ts) to my component tag " ...

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

What is the best way to trigger an API call every 10 seconds in Angular 11 based on the status response?

I am in need of a solution to continuously call the API every 10 seconds until a success status is achieved. Once the success status is reached, the API calls should pause for 10 seconds before resuming. Below is the code I am currently using to make the A ...

Is it possible for Angular 7 to disconnect from the internet?

I am looking to disable all buttons, clicks, and hyperlinks while displaying a backdrop with the message "GO ONLINE". It may come off as rude, but it is necessary. AppComponent (TS): The connectionMonitor can be used to monitor network connectivity. pr ...

How can I efficiently make a dropdown menu with search functionality instead of using datalist?

I am currently working on creating a custom searchable input field that makes backend calls. Instead of using datalist, I want to design a unique UI with ul and li items. While I have successfully implemented the search functionality, I am facing a glitc ...

The function angularCompiler.getNextProgram is not available in the context of angular 12 when using custom-webpack configurations

Recently, I upgraded my Angular 11 project to version 12. I have incorporated the @angular-builders/custom-webpack package in my devDependencies and I am using the below command for building my Angular project. ng build --configuration=production --build ...

Node.js encountering an error caused by a lengthy SQL procedure execution, triggered by a POST request initiated from

Currently, my website utilizes Angular, NodeJs, and a SQL database. Most of the site's calls are made from the frontend to the backend and everything runs smoothly. However, I encountered an issue when running a stored procedure that had a longer proc ...

Utilize Angular 2 with Google Maps Places Autocomplete to dynamically update an input field with location suggestions [DOM manipulation]

Recently, I have been utilizing the "Angular 2 + Google Maps Places Autocomplete" search functionality. Essentially, it involves an input field that looks like this: <input placeholder="search your location" autocorrect="off" autocapitalize="off" spell ...

When working with Angular 2, it is important to note that the NgFor directive only supports binding to Iterables like Arrays. If you encounter an error message stating "Cannot find a differ supporting object '[object Object]' of type 'leaveType

After an extensive search and exploration for a solution to my problem, I found one, but unfortunately it didn't work as expected. The issue at hand involves displaying static data/list in dropdown options using TypeScript. Currently, I am working wit ...

Angular: Issue with object instantiation - Unable to assign property

Having trouble populating my array due to instantiation issues. Defined Models: user: User = { firstName: "", lastName: "", address: "" } order: Order = { OrderId: "", User: this.user, TotalPrice: 0, OrderItems: [] } Attempting to populat ...

Exploring Angular (5) http client capabilities with the options to observe and specify the response type as 'blob'

Situation: I'm facing a challenge in downloading a binary file from a backend system that requires certain data to be posted as JSON-body. The goal is to save this file using File-Saver with the filename specified by the backend in the content-disposi ...

Retrieve information from the local storage every second

I have developed a new application using Angular 8. Within this component, I have created a model where users can select an option. I wrote a function in the TypeScript file to store this information in local storage. Now, I need assistance with retrieving ...

"Implementing legends in charts with c3.js and JSON data: A step-by-step guide

Utilizing the C3 chart library to showcase data in my project, I aim to display legends (labels) instead of numbers on the AxisX: Data JSON format: [ {"Label":"DQUA","Aut":3.75,"NoAut":3.75,"CM":32}, {"Label":"DPRO","Aut":43.9,"NoAut":0,"CM":144} ...

The issue arises when trying to use data provided by a service, resulting in an "undefined

Looking to create a handler that generates an array of categories based on the presence of "categories" for a specific "resource". However, encountering an error with the last method. ERROR TypeError: "this.allProjectResources is undefined" import { Res ...

Column spilling over with cards

Having a card with a form in it, I wanted to implement a y-scroll bar to control the visibility of the form on the page. However, it seems that the columns are extending beyond the boundaries of the card. .card { box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2 ...

Encountered an execution policy error while trying to run the "yo office" command in the Yeoman office add-in generator

I was eager to use Yeoman to develop an Office add-in with Angular. After successfully installing the necessary tools such as Node.js, Angular, Yeoman, and generator-office in PowerShell, I attempted to run the following code: yo office Unfortunately, I e ...

Error Message: Angular Unit Test Fails with "Cannot read property 'subscribe' of undefined"In this article, we will

My Angular app's unit tests using Jest are giving me the error "TypeError: Cannot read property 'subscribe' of undefined". Despite searching online, none of the solutions provided seem to work for me. Below is some relevant code: page-view. ...