Acquire information from the user interface and display it in a highcharts chart using Angular 5

Currently, I am utilizing an npm package for chart creation, which can be found at the following link: https://www.npmjs.com/package/angular-highcharts

I have a specific interface set up and I aim to extract values from this interface to populate a line graph within the chart. My main goal is to display a line graph at this point in time.

After experimenting with different array methods, I discovered that initializing the array with hardcoded values works perfectly fine. However, my objective is to dynamically load values from a service into an interface and then transfer these values from the interface to the chart. What could be causing this issue?

Below is the contents of my component.ts file:

import { Component, OnInit } from '@angular/core';
import { Chart } from 'angular-highcharts';
import { WeatherstatsService } from '../weatherstats.service';
import 'rxjs/add/operator/map';

interface WeatherData {
  id: any;
  year: any;
  measurement_type: string;
  location: string;
  month_or_season: string;
  value?: any;
}

let datavalues: WeatherData [] = [];

@Component({
  selector: 'weatherchart',
  templateUrl: './weatherchart.component.html',
  styleUrls: ['./weatherchart.component.css']
})
export class WeatherchartComponent implements OnInit {

  constructor(private weatherstatsservice: WeatherstatsService) { }

  title = "Title";
  data: any;
  datavalues = datavalues;
  values: Array<number> = [];

  chart = new Chart({
        chart: {
          type: 'line'
        },
        title: {
          text: this.title,
        },
        credits: {
          enabled: false
        },
        series: [{
          name: 'Line 1',
          data: this.datavalues.year,
        }]
      });

    // add point to chart serie
    add() {
      this.chart.addPoint(Math.floor(Math.random() * 10));
    }

    ngOnInit() {
          this.weatherstatsservice.getWeatherData()
            .subscribe(data => {
              this.data = data.slice(0, 100);
             if(this.data){
              this.data.forEach( res => {
                this.datavalues.push({
                  id: res.id,
                  year: res.year,
                  measurement_type: res.measurement_type,
                  location: res.location,
                  month_or_season: res.month_or_season,
                  value: res.value,
                })
               });
               console.log(this.datavalues);

            }
        })
      }


    }

Answer №1

Dealing with issues in libraries is a common occurrence, and I recently encountered a similar problem with ng2-charts. The solution lies in redrawing the chart using the API.

To achieve this, you can pass the chart instance like so:

<chart [options]="options" (load)="saveInstance($event.context)"></chart>

In your TypeScript file:

chart: Object;
saveInstance(chartInstance): void {
     this.chart = chartInstance;
}

When receiving data from an API, you can then redraw the chart by updating the series:

updateSeries(data: Array<any>): void {
   this.chart.series[0].setData(data);
}

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

CSS not working when attempting to override Angular (13) Material file

In my Angular (13) application with Material, I have developed a CSS file specifically for overriding certain Material styles. This CSS file is imported into the styles.scss file as the last line. However, despite importing the external file, the CSS def ...

Navigating the Angular2 @angular/router 3.0.0-alpha.3 - Ways to access the route name or path upon route transitions

In my app.component, I am currently looking for a way to access the current route name or path when the route changes. My goal is to use the route name as a page class for a wrapper div. I had previously been subscribing to the router changes property as ...

Instead of relying on Vue TypeScript, we are leveraging IntelliJ with TypeScript 5.0.3 to compile our Vue project

My current version of IntelliJ IDEA is 2023.1 (Ultimate Edition) Build #IU-231.8109.175, released on March 28, 2023. I am facing an issue where my project fails to compile using "Vue TypeScript", resulting in some type mismatches being overlooked. In the ...

What distinguishes ReadonlyArray from the declaration "readonly arr: T[]"?

Check out this unique playground. interface Feature { readonly name: string; } // <Test> // This is OK interface Foo1 { readonly arr: ReadonlyArray<Feature>; } function save1(foo: Foo1) { console.log(foo); } // </Test> // <Tes ...

Expect a reply within the loop

One of my endpoints takes some time to generate data, and I have another endpoint to retrieve that generated data. I make the initial call using await, extract the ID from the response, and then keep calling the second endpoint until the status is not "Suc ...

Path for WebStorm file watcher's output

I'm in the process of setting up a Typescript project in WebStorm, where I want the files to be transpiled into a dist folder. This is my current project folder structure: projectroot/src/subfolder/subfolder/index.ts What I aim for is to have the f ...

How can you generate a distinct id value for each element within an ngFor iteration in Angular 4?

I encountered an issue where I must assign a distinct id value to each data row within my *ngFor loop in angular 4. Here is the code snippet: <div *ngFor="let row of myDataList"> <div id="thisNeedsToBeUnique">{{ row.myValue }}</div> & ...

Tips for validating the request body prior to sending in Angular unit testing

I'm experiencing some difficulties creating a unit test. Despite reading numerous articles, none have proven to be helpful in simplifying the process. The specific function I need to test returns an Observable. My main objective is to ensure that myB ...

The ngOnChanges method does not fire when the input value changes

Here is an example of my Angular component: @Component({ selector: 'request-Component' templateUrls: './request.component.html' styleUrls: ['./request.component.scss'] }) export class ChildComponent implements OnIn ...

Angular Error: The function is expecting a different type of input than what is being provided

Currently in the process of learning angular, I have a goal to create a service with a boolean observable and subscribe to it. I stumbled upon this tutorial that aligns closely with what I want - hiding menu nav links when a user is not logged in. In my ...

The operation of assigning the value to the property 'baseUrl' of an undefined object cannot be executed

I recently created a JavaScript client using NSWAG from an ASP .NET Rest API. However, I am encountering some errors when attempting to call an API method. The specific error message I am receiving is: TypeError: Cannot set property 'baseUrl' of ...

Finding the location of an "Apply" button on an Angular HTML page

There is an issue with the positioning of the apply button in the filter bar. Sometimes it displays in the next row instead of alongside the other filters. How can I determine the exact position of this apply button within the HTML page? <div class=&quo ...

The const keyword is not automatically inferred as a const when using conditional types for generic type parameters

Within Typescript, the const modifier can be applied to function type parameters. This ensures that the inferred type matches the literal received with as const. function identity<const T>(a: T){ return a } For example, when using identity({ a: 4 ...

Retrieve the structure from a React application

When it comes to documenting architecture, the process can be incredibly beneficial but also quite time-consuming and prone to becoming outdated quickly. I have come across tools like Doxygen that are able to extract architectural details such as dependen ...

Utilize prop-types inheritance when a component is rendered via props

Is it possible to inherit prop-types when a component is rendered via the parents prop, without direct access to 'ChildProps' and 'Props' interface? Parent Component interface ChildProps { counter: number; setCounter: React.Dispat ...

Angular 8 does not allow for the assignment of type '{}' to a parameter

I have a unique approach for managing errors: private handleErrors<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); this.record(`${operation} failed: ${error.m ...

A TypeScript/Cypress command that restricts input parameters to specific, predefined values

I have a Cypress command with a parameter that I want to restrict so it only accepts certain values. For example, I want the columnValue to be limited to 'xxx', 'yyy', or 'zzz'. How can I achieve this? Cypress.Commands.add( ...

Issue with comparing strings in Typescript

This particular issue is causing my Angular application to malfunction. To illustrate, the const I've defined serves as a means of testing certain values within a function. Although there are workarounds for this problem, I find it perplexing and woul ...

Creating a new project in ASP Net Core Angular using Bootstrap 4 for the SideMenu layout instead of Bootstrap 3

I am currently working on developing a website using Angular6, where I aim to have a vertical navbar for large screens and a top navbar with dropdown functionality for mobile devices. While searching online, I came across several examples that seemed overl ...

Angular Error: Cannot call function panDelta on this.panZoomAPI

Check out my small demonstration using a stackblitz, I'm having an issue. In the setup, there's a master component with pan-zoom functionality containing a parent component with children content. The library in use is ngx-panzoom. The default c ...