Angular HighCharts - Retrieving chart data via API

My goal is to populate the data property of my chart with values obtained from an external API: .

I've defined an Interface that matches the structure of the data:

export interface ChartData{
        item1: number;
        item2: number;
    }
    

This snippet represents how my chart looks like:

chartOptions: Options = {
        title: {
          text: 'CDF of the most frequent update frequency',
          style: {
            color: 'whitesmoke'
          }
        },
        chart: {
          type: 'line',
          zoomType: 'x',
          backgroundColor: '#323232',
        },
    
        ...
    
        series: [],
    
        ...
    
      };
    

I am now attempting to assign the retrieved data (from the API) to the data property inside the series. Here's a hardcoded example:

series: [
      {
       data: [[1, 2], [2, 4], [3, 7] ...] 
    

The first value in each pair corresponds to the x-axis, and the second value relates to the y-axis. The ChartData Interface also follows this pattern: item1 represents the x-axis value, and item2 represents the y-axis value. Below is my implementation:

ngOnInit(): void {
        this.chartService.getMostFrequentUpdateData().subscribe(
          (data: ChartData[]) => {
            this.chartOptions.series = [
              {
                name: 'ao',
                type: 'line',
                data: data,
                color: '#009879',
              }
            ];
          });
    }
    

An error is encountered stating Type 'ChartData[]' is not assignable to type '(number | PointOptionsObject | [string | number, number | null] | null)[]'. I realize ChartData should actually be an ARRAY containing two numbers instead of just two numbers which seems to be causing the issue.

For further clarification, here's the http call within my service:

getMostFrequentUpdateData(): Observable<ChartData[]>{
        return this.http.get<ChartData[]>('https://bgpie.net/api/rrc/00/mostfrequentstatefrequencycdf');
      }
    

You can access the project on GitHub: https://github.com/mauri5566/sitocopy/blob/master/src/app/components/home/modal-most-frequent-update/modal-most-frequent-update.component.ts. Please note there might be merge conflicts present.

EDIT: Despite making adjustments based on suggestions, the data still remains invisible on the chart. Using console.log confirms that chartData holds the following values:

0: (2) [0, 0]
    1: (2) [1, 98.60093378412567]
    2: (2) [2, 99.69295521976126]
    3: (2) [3, 99.79668345638125]
    ...
    

The way these values are structured appears accurate as they form pairs. The structure of the ChartData Interface has not changed. Below is how I handle ngOnInit:

chartDataX: number[] = [];
    chartDataY: number[] = [];
    chartData: any[] = [];

    ngOnInit(): void {
        this.chartService.getMostFrequentUpdateData().subscribe(
          (data: ChartData[]) => {
            for (let i = 0; i < data.length; i++){
              this.chartDataX.push(data[i].item1);
              this.chartDataY.push(data[i].item2);
              this.chartData.push([this.chartDataX[i], this.chartDataY[i]])
            }
          });

        this.chartOptions.series = [
          {
            name: 'ao',
            type: 'line',
            data: this.chartData,
            color: '#009879',
          }
        ];
    }
    

Answer №1

Yes, your suspicions are on point. The series data should consist of either an array of numbers, an array of arrays containing numbers, or an array of objects with at least x and y values.

  • Array<number>,
  • Array<Array<number>> or
  • Array<Object> where in object you have at least x and y.

To see how the data should be structured, refer to this link: https://api.highcharts.com/highcharts/series.line.data

To rectify this issue, I recommend creating two separate arrays named item1 and item2. When fetching data, populate each array accordingly with the data points. Then, pass these arrays to the chart for display.

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

Updating or adding an item to a Firestore query using Angular

Need help updating or adding an item in my Firestore query. I attempted the following code snippet, but unfortunately, it did not update as expected. Any suggestions on how to ensure 'chatusers' gets updated correctly? chatsuserCol: AngularFire ...

The URL for my JSON file cannot be located on my Angular server

Hey there! I'm currently working on setting up a server that will be pulling product data from a JSON file using HTTP. However, I've encountered an issue during the application build process where this error message pops up: Failed to load resou ...

Issues arising post transitioning to 14.0.0 from 13.0.0 version of ngx-masonry library leading to failed tests

Following the update to the latest stable version of the library ngx-masonry 14.0.0, our tests started failing. The release was just yesterday (24.10.2022) and you can find the changelog here: https://github.com/wynfred/ngx-masonry/blob/master/CHANGELOG.md ...

Exploring the concept of relative routing within Angular

Update I made the switch from forRoot to forChild based on the responses received. Essentially, I have two issues to address. Let's consider this as a submodule: @NgModule({ imports: [ CommonModule, ARoutingModule, BModule ], decl ...

The Angular build is unsuccessful due to the presence of components from a separate Angular project

Whenever I execute ng build project1 --prod, the build fails and displays this error message: ERROR in : Cannot determine the module for class MyComponent in .../project2/app/my.component.ts! Add MyComponent to the NgModule to fix it.. Although the sol ...

I am experiencing difficulties in assigning values to a formArray

I am struggling to update values in an array form, as I am facing challenges setting new values. Although I attempted to set values using patch value, my attempts were unsuccessful. // Component.ts this.packageForm = this.formBuilder.group({ title: [&a ...

Navigating through complex routes was tricky in Next.js 14 due to the error 404 on hard navigation with

While working on implementing tab groups using Parallel Routes in Next.js 14, I encountered an issue where a 404 page only appears during hard navigation to /gnb/mypage/tab1. The tabs and their navigation function properly on initial render and when switch ...

What's the best way for me to figure out whether type T is implementing an interface?

Is it possible to set a default value for the identifier property in TypeScript based on whether the type extends from Entity or not? Here's an example of what I'm trying to achieve: export interface Entity { id: number; // ... } @Compon ...

Issue with Angular 5 HttpClient - PUT request not working in Firefox, however functions correctly in Chrome

Currently in the process of developing a website with Angular 5 and CouchDB. One of my methods in database.service.ts looks like this: import {HttpClient} from '@angular/common/http'; const auth = my database adress; constructor(private http: Ht ...

Experiencing a compilation issue while attempting to apply the class-transformer

Encountering an issue while working with a basic example that involves class-transformer. error TS1240: Unable to resolve signature of property decorator when called as an expression. Argument of type 'ClassFieldDecoratorContext<Root, Project[]> ...

Injecting Variables Into User-Defined Button

Presenting a custom button with the following code snippet: export default function CustomButton(isValid: any, email: any) { return ( <Button type="submit" disabled={!isValid || !email} style={{ ...

Subscribing to a GraphQL mutation through Angular with the Appsync client

Currently, I am developing a chat application in Angular using GraphQL with Appsync on AWS. The current process for creating a new chat involves mocking up the chat and sending it to the server. On the server-side, a unique chat_id is generated for each ch ...

Angular 8 template-driven form encountering a Minimum Length Error

Upon clicking the submit button, I encountered the following error: ERROR TypeError: Cannot read property 'minlength' of null I am unsure why this error is happening. How can I go about resolving this issue? Below is the code from app.componen ...

What methods can I utilize from Google Maps within Vuex's createStore()?

Currently, I am in the process of configuring my Vuex store to hold an array of Marker objects from the Google Maps Javascript API. Here is a snippet of how my createStore function appears: import { createStore } from "vuex"; export default ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...

What is the best technique for verifying the existence of data in the database before making updates or additions with Angular's observables?

I am facing a straightforward issue that I need help with in terms of using observables effectively. My goal is to search my database for a specific property value, and if it exists, update it with new data. If it does not exist, then I want to add the new ...

"Troubleshooting: Angular Animation feature not functioning properly with MDB Bootstrap

Struggling to incorporate the mdb-bootstrap animation into my angular project, but it's not working as expected. I followed the instructions for basic mdb animation from MDB Bootstrap Animation. While it works in MDB EDITOR, when I insert the same cod ...

Angular script error when running 'npm run' on select computers causing Unix command issues for some users but not all

Recently, I've encountered a puzzling issue at my workplace that has been difficult to diagnose. We utilize scripts in npm within the Angular framework to launch a local server instance. Strangely enough, some of my colleagues' computers are thro ...

Enhance Graphql Queries with TypeOrm using Dynamic Filters

I am currently working on building a graphQL query system using Apollo, typescript, and TypeOrm. At the moment, I only have one table called users in my database. I am creating a getUsers GraphQL query which retrieves all users from the table. With the hel ...

Should FormBuilder be utilized in the constructor or is it considered a poor practice?

section, you can find an example of implementation where declarations for formBuilder and services are done within the constructor(). While it is commonly known that using services inside the constructor() is not a recommended practice and should be done ...