Utilizing information retrieved from an HTTP post response in Angular 4 for Highcharts seems to be unsupported

My goal was to retrieve data from a Http Post response and display it as a data series in Highcharts. This is the approach I took:

simplechart.component.ts:

import { Component, OnInit } from '@angular/core';
//import { ChartModule } from 'angular-highcharts';
import { Chart } from 'angular-highcharts';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';

interface UserResponse {
    login: string,
    bio: string,
    company: string
}

@Component({
  selector: 'app-simplechart',
  templateUrl: './simplechart.component.html',
  styleUrls: ['./simplechart.component.css']
})
export class SimplechartComponent implements OnInit {

    // Your code here...

simplechart.component.html:

<div [chart]="chart"></div>

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { ChartModule } from 'angular-highcharts';
import { AppComponent } from './app.component';
import { SimplechartComponent } from './components/chart-demo/simplechart/simplechart.component';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    SimplechartComponent

  ],
  imports: [
    BrowserModule,
    ChartModule,
    HttpClientModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts:

import { Component, OnInit  } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

package.json:

{
  "name": "charts",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,

  // Dependencies

  "description": "This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.3.0.",
  "main": "karma.conf.js",
  "author": ""
}

It seems like the Highchart layout is displaying but not the values. Any ideas on how to troubleshoot this issue? You can check the picture here.

Answer №1

To ensure the chart variable is accessible outside the subscribe function, it must be declared beforehand:

export class SimplechartComponent implements OnInit {
chart:any; //Declare the chart variable here to use it in your template
/...

//Fill the chart variable within your subscribe function without redeclaring it.
/...
var datas:any[]=[];
for (var i = 0; i < data['data'].length; i++) {
       datas.push(+data['data'][i]['count']);
     }
/...
this.chart = new Chart({
             chart: {
               type: 'line'
             },
             title: {
               text: 'Linechart'
             },
             credits: {
               enabled: false
             },
             xAxis: {
                   categories: appid
             },
             series: [{
                   name: 'appid',
                   data: datas //Array used in your code
                 }]
               });

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

What is the best way to refresh content in a secondary component when a websocket event is received by the primary component?

My Component A has a websocket logic that looks like this: this.socketService.connect('/socket_url'); this.statusSubscription = this.socketService.messages .subscribe(result => { if (result !== 'pong') { ...

Tips for obtaining an Instance of a Mat-Table when there are multiple tables within the component

Encountering an issue where I have a component in Angular 6 generating multiple Mat-Tables with Data. Using the ng-for loop to iterate through all the Mat-Table Data sources within a div tag. However, when trying to add a new row to a table, unable to iden ...

Using ANGULAR 5, you can easily pass a function down to a child

My component "Calendar" includes a child called "Month". export class MonthCalendarComponent { @Input() holidayClicked: (day: Date) => Observable<boolean>; dayClicked(day: CalendarMonthViewDay): void { this.holidayClicked(day.date).subsc ...

Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material. During testing of my component (refer to the simplified code below), I encountered the following error: Error: Error in ./MdTabHeader class MdTabHeader - ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

The data set in a setTimeout is not causing the Angular4 view to update as expected

I am currently working on updating a progress bar while importing data. To achieve this, I have implemented a delay of one second for each record during the import process. Although this may not be the most efficient method, it serves its purpose since thi ...

What is the best way to substitute a component in @viewChildren with a test double?

If I have a test that involves a component which uses a complex component and interacts with it through references obtained via @viewChildren, how can I substitute the complex component with a test double in `TestBed'? Here's an example: @Compo ...

When a radio button is clicked in Angular7 and it shares the same form control name, both radio buttons are being

Visit this StackBlitz link for more information. places = ['effil tower','new discover'] new FormGroup({place: new FormControl()}); <div *ngIf="places?.length > 0" class="col-12"> <div style=" padding-top: 1e ...

Having trouble with errors when adding onClick prop conditionally in React and TypeScript

I need to dynamically add an onClick function to my TypeScript React component conditionally: <div onClick={(!disabled && onClick) ?? undefined}>{children}</div> However, I encounter the following error message: Type 'false | (() ...

Angular subscription unsubscription issue

I have noticed that my Angular application has a significant amount of event hooks and subscriptions which are causing performance issues. Initially, the app functions well but after continued usage, it becomes slow with typing delays of around 2 to 3 seco ...

Filter the angular accordion by passing a simple array value into the input

I am looking to filter my array of accordion items based on the value of the question matching the input I provide. I have tried using the filter method for this. this.accordionItems = [ { "topic":"polizze", " ...

Creating a Persistent Top Navigation Bar using Bootstrap and Angular

I am struggling to implement a fixed top navbar in Angular. The structure of my main app.component template is as follows: <page-header></page-header> <router-outlet></router-outlet> The bootstrap navbar is included within my ...

Using TypeScript to utilize an enum that has been declared in a separate file

Imagine I have defined an enum in one file (test1.ts): export enum Colors{ red=1, blue=2, green=3 } Then in another file (test2.ts), I am creating a class with a method. One of the parameters for that method is a Color from the Colors enum: ...

Enable the use of unfamiliar techniques on object

I am facing a challenge with an object that contains multiple method names which are not known at compile time. The signature of these methods always remains the same, but I am unsure about how to handle this scenario. I attempted to utilize an index type ...

Navigating the parent navController in Ionic 2: A step-by-step guide

I'm currently honing my skills in Ionic 2 by creating a basic app, but I've encountered an issue that has me stumped. The app features an ion-nav element for the login page, then transitions to a tabs navigator after successful login. The struct ...

Is there a way to determine if a browser's Storage object is localStorage or sessionStorage in order to effectively handle static and dynamic secret keys within a client?

I have developed a customizable storage service where an example is getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage())) in typescript/javascript. When implementing getSecureStorage, I used a static cipher key to encrypt every ke ...

What exactly is involved in the authentication process, and what steps can be taken to safeguard against cyber threats posed by skilled hackers like

In my current project, I am developing an Angular + ASP.NET MVC application without using built-in tools like Claims, JWT, and others. My custom authentication system involves a "Users" table: namespace AwakenedTalents.Models { public class User { ...

Despite rebuilding, the content in the Angular application does not refresh upon making changes

My current project involves using ASP.Net core Web API as the backend with an Angular app on the frontend. I decided to customize my Angular project rather than using the default SPA template provided. To achieve this, I created a blank ASP.NET Core projec ...

using the ng2-accordion component in your Angular 2 project

I am having trouble with the angular-2 accordion I implemented. It is not functioning properly and throwing a 404 error. The issue seems to be related to a third-party plugin called "ng2-accordion." I have double-checked the path of the package and it is ...

Angular: When making an HTTP GET request, receiving an OPTIONS 405 error message indicating that the method is

I'm facing an issue with my API when making an HTTP GET request - it returns OPTIONS 405 (Method Not Allowed). Access to XMLHttpRequest at 'apiurl' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to ...