Utilizing the power of JSON data in conjunction with the angular2-high

I am attempting to generate a chart using JSON data with the help of angular2-highcharts. The structure of my ChartsMain component is as follows:

@Component({
moduleId: module.id,
selector: 'charts',
templateUrl: 'charts.html',
directives: [CHART_DIRECTIVES,]
providers: [DataService]
})
export class ChartsMain {

result: Data[];

constructor(DataService:DataService) {
    DataService.getData().subscribe(res => this.result = res);
        this.options = {
            chart: {
                type: "candlestick"
            },
            title: {
                text: "JSON data"
            },
            xAxis: {
                type: "category",
                allowDecimals: false,
                title: {
                    text: ""
                }
            },
            yAxis: {
                title: {
                    text: "Number"
                }
            },
            series: [{
                name: "Hour",
                data: this.result
            }]
        };
}
options: Object;

Additionally, here is how my DataService is structured:

@Injectable()
export class DataService {

http: Http;
constructor(http: Http) {
    this.http = http;
}


getData(): Observable<Array<Data>> {
    return this.http.get('http://JSON-DATA')
        .map(this.extractData)
        .catch(this.handleError)
}

private extractData(res: Response) {
    let body = res.json();
    return body || { };
}
private handleError(error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
}
}

This is what my chart looks like.

I seem to be encountering an issue as my chart is currently empty. Any insights on why this might be happening and how I can successfully populate the chart with JSON data? Is there a specific format that the JSON data must adhere to?

Answer №1

A candlestick chart is commonly utilized to display the open, high, low, and close prices over a specific period.

An example of the expected JSON format is as follows-

[
[1250553600000,23.09,23.46,23.06,23.43],
[1250640000000,23.25,23.61,23.21,23.51],
[1250726400000,23.57,23.82,23.52,23.76],
[1250812800000,23.95,24.20,23.83,24.17],
[1251072000000,24.30,24.39,24.04,24.15],
[1251158400000,24.21,24.42,24.16,24.20],
[1251244800000,24.13,24.22,23.82,23.92],
[1251331200000,24.11,24.22,23.55,24.21],
[1251417600000,24.61,24.64,24.08,24.29],
[1251676800000,24.02,24.12,23.79,24.03],
]

Here is an example component featuring a candlestick highchart-

import { Component } from '@angular/core';
import {JSONP_PROVIDERS, Jsonp} from '@angular/http';
import { CHART_DIRECTIVES } from 'angular2-highcharts';


@Component({
    selector: 'high-chart',
    directives: [CHART_DIRECTIVES],
    providers: [JSONP_PROVIDERS],
    template: `
    <h2> This is HighChart CandleStick component </h2>

        <chart type="StockChart" [options]="options3"></chart>
    `
})

export class HighChartsComponent {

    options3: Object;

    constructor(jsonp : Jsonp) {

        jsonp.request('https://www.highcharts.com/samples/data/jsonp.php?a=e&filename=aapl-ohlc.json&callback=JSONP_CALLBACK').subscribe(res => {
            this.options3 = {
                title : { text : 'CandleSticks' },
                rangeSelector : {
                    selected : 1
                },
                series : [{
                    type : 'candlestick',
                    name : 'CandleSticks',
                    data : res.json(),
                    dataGrouping : {
                    units : [
                        [
                            'week', // unit name
                            [1] // allowed multiples
                        ], [
                            'month',
                            [1, 2, 3, 4, 6]
                        ]
                    ]
                },
                    tooltip: {
                        valueDecimals: 2
                    }
                }]
            };

        });
}

EDIT:

In your situation, ensure that you set the chart options inside the subscribe function like so-

        this._http.get('http://knowstack.com/webtech/charts_demo/data.json')
                .map(this.extractData)
                .subscribe((response) => {
                    this.options = {
                                    title : { text : 'knowstack' },
                                    series : [{
                                        name : 'knowstack',
                                        data : response.json()
                                    }]
                                };
                },
                (error) => {  
                    this.errorMessage = <any>error
                });

Please note that data from knowstack will only be compatible with simple charts, not candlestick charts.


EDIT 2: column chart

Refer to the configuration below for utilizing a column chart.

this.options1 = {
            title : { text : 'simple column chart' },
            series: [{
                type : 'column',
                data:  [["Maths",15],["Physics",16],["Biology",18],["Chemistry",19]]
            }]
        };

EDIT 3: sample of key-value pair json

import { Component }        from '@angular/core';
import { CHART_DIRECTIVES } from 'angular2-highcharts'; 

@Component({
    selector: 'my-app',
    directives: [CHART_DIRECTIVES],
    styles: [`
      chart {
        display: block;
      }
    `]
    template: `<chart [options]="options"></chart>`
})
class AppComponent {
    constructor() {
        var data = [{"key":"Math","value":98},{"key":"Physics","value":78},{"key":"Biology","value":70},{"key":"Chemistry","value":90},{"key":"Literature","value":79}];

        this.options = {
            title : { text : 'simple chart' },
            xAxis: {
                type: 'category'
            },
            series: [{
                data: data.map(function (point) {
                    return [point.key, point.value]; 
                })
            }]
        };
    }
    options: Object;
}

Answer №2

Great news, the solution is working smoothly. I utilized a service mentioned in my previous post, but made some adjustments to the component:

constructor(http: Http, jsonp : Jsonp, DataService:DataService) {
        DataService.getData().subscribe(res => this.result = res);
        http.request('').subscribe(res => {
            this.options = {
                chart: {
                    type: 'column'
                },
                plotOptions: {
                    column: {
                        zones: [{
                            value: 12, 
                        },{
                            color: 'red' 
                        }]
                    }
                },
                series: [{
                    data: this.result 
                }]
            };
        });
    }
    options: Object;

Now, let's focus on the JSON data at hand:

[{"key":"Math","value":98},{"key":"Physics","value":78},{"key":"Biology","value":70},{"key":"Chemistry","value":90},{"key":"Literature","value":79}]

I'm interested in splitting this data similar to what is shown here:

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

The issue with the antd Input component's onChange event not updating state correctly when using a list fetched from an axios get request in a React

Recently delving into React, I've dedicated the past week to honing my skills. My current project involves creating a straightforward application featuring a 'product create' form alongside a product list equipped with a search bar (utilizin ...

tips for changing a json string into yaml format

I am facing an issue with the given code snippet: string stringXDoc = JsonConvert.SerializeObject(ConnectedItemOperations.GetConnectedItemById(id).Edits.EditableData); var json = JsonConvert.DeserializeObject(stringXDoc); The specific file is triggeri ...

Error encountered in setting the position of a Google Maps marker due to incorrectly nesting a Google Maps latLng object in JSON

I keep encountering an error that I can't quite pinpoint the reason for. It seems that a google.maps.latLng object nested within some json is causing an issue, specifically: Error: Invalid value for property : (-19.240542583932452, 148.15044705312494 ...

Create a Typescript generic function that can return a variety of data types including strings, numbers, and

I have a function written in Typescript and I am looking to determine the return type based on the value retrieved from process.env. For instance, the variables in my Node process.env can be strings, numbers, or booleans. I want to fetch them with their s ...

Navigating through different components in Angular2 is made simple with the

Struggling to create a single-page app and facing issues with routing. Despite following several tutorials, I find them quickly becoming outdated due to Angular2 still being in beta. Whenever any reference to router directives, configurations, or provider ...

What are the best practices for implementing MapLabel in an Angular project?

I need help displaying text on top of multiple polygons on a map. I've heard that Map Label can help with this, but I'm having trouble implementing it and can't find any NPM resources. Here is the Stack Blitz URL for reference: https://stac ...

Efficiently implementing state and dispatch for useReducer in TypeScript with React

I'm encountering an error in my current setup. The error message reads: 'Type '({ team: string | null; } | { team: string | null; } | { ...; } | { ...; } | { ...; } | Dispatch<...>)[]' is missing the following properties from t ...

Retrieve the JSON path for a specific value using Jackson

I am attempting to extract the JSON path of a value from a JSON string using Jackson. Since I couldn't find any built-in function in Jackson that provided this functionality, I decided to create my own custom function. Here is the function I came up ...

What is the process for consumers to provide constructor parameters in Angular 2?

Is it possible to modify the field of a component instance? Let's consider an example in test.component.ts: @Component({ selector: 'test', }) export class TestComponent { @Input() temp; temp2; constructor(arg) { ...

pnpm, vue, and vite monorepo: tackling alias path imports within a workspace package

I am in the process of creating a monorepo for UI applications that utilize shared components and styles with pnpm, typescript, vue, and vite. While attempting to streamline development and deployment using pnpm's workspace feature, I am encountering ...

Is there a function that provides a value based on an assertion?

I have been working on creating a function with the following structure: function validate<T>(input: T, message?: string): T & asserts input { if (!input) { throw new Error(message) } return input } The main aim of this function is to ...

Expand the font manually

Is there a way to define a type that represents the widened version of another type? Consider the following scenario: function times<A extends number, B extends number>(a: A, b: B): A & B; The intention behind this times function is to preserv ...

NodeJS's JSONStream package delivers data in a continuous, uninterrupted string format

I am currently working on parsing a large JSON file containing 300k lines in Node using JSONStream. According to the documentation, I expected that by using the code below, only the first 10 rows of the document would be displayed on the console. However, ...

The use of Ajax JQuery to retrieve data from a MySQL database using PHP is not functioning properly when attempting to handle

I spent hours working on this but couldn't find a solution on your website. I have a jsonTable.php file that connects to a database and returns JSON using echo: { "livres": [{ "titre": "John", "auteur": "Doe", "annee": ...

Send a JSONArray using Volley and fetch a StringresponseData

I am new to android development and currently exploring the use of volley for networking. I have a query regarding sending a JSONArray via a POST request using volley and expecting a String response. After downloading the volley files from Github, I found ...

What is the best way to define a precise return type for a JSX Element?

Is it possible to define a function that returns a Button element and what would the correct return type of the function be? For example: Ex: const clickMeButton = (): Button => { return ( <Button> Click Me </Button& ...

At which point during the lifecycle of an Angular application should the JWT token be refreshed

As a new Angular user, I am uncertain about where to refresh an access token. I am familiar with guards and interceptors, but I need guidance on the best approach and any potential trade-offs. Many tutorials cover the "how" but lack insights into the "why" ...

What is the most effective way to remap all property names while serializing using Json.NET?

When converting a Json object to a .Net type, if the field names do not match up, you can use [JsonProperty(PropertyName = "name")] to map properties in your type. This method works well for individual properties with mismatched names. But is there a way ...

Steer clear of including numerous variable values in Angular 2 while adjusting the class of selected items

Here's a question from someone who is new to Angular 2 and looking for an efficient way to change the active CSS class of tabs without using the router: activeTab: string; switchActiveTab(newTab: string) { this.activeTab = newTab; } <div clas ...

Transforming a function into an array in TypeScript

I attempted to use the map() function on a dataURL array obtained from the usePersonList() hook, but I am struggling to convert my function to an array in order to avoid errors when clicking a button. import Axios from "axios"; import React, { us ...