2

I want to create chart based on the JSON data. I using angular2-highcharts my ChartsMain component looks like:

@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;

And my DataService looks:

@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);
}
}

My chart

Where is a problem, why is chart empty? How do I fill the chart with JSON data. JSON data must be in any specific format?

Eugene Gluhotorenko
  • 3,094
  • 2
  • 33
  • 52
Marko
  • 227
  • 2
  • 6
  • 13
  • 1
    can you share your JSON data? – Sanket Aug 16 '16 at 10:17
  • yes, my JSON data are: [ { Id: 1, Name: "Name1", ProductId: 2, ProductName: "ProductName1", StartMonth: "2016-01-01T00:00:00", EndMonth: "2016-01-01T00:00:00", Number1: 1, Number2: 2, ProductDetail: [ { Id: 101, OrderId: 1001, ProductionMonth: "2016-01-01T00:00:00", OrdersCount: 10, StorageCount: 1, ProductAll: null } ] }, ] – Marko Aug 16 '16 at 12:12

2 Answers2

3

A candlestick chart is typically used to present the open, high, low and close price over a period of time..

Sample expected JSON format looks like this-

[
[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 sample component with 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 case you are not setting chart options inside subscribe. You should set like this-

        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 - data from knowstack will only work with simple charts (not candlestick)


EDIT 2: column chart

Please refer below configuration. This is how you can use 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;
}
Sanket
  • 19,295
  • 10
  • 71
  • 82
  • So i cant use other json format? When i use sample component and give url for my json i get this: EXCEPTION: Response with status: 200 Ok for URL: – Marko Aug 16 '16 at 12:00
  • I don't think candle stick other json format. can you share your JSON data? I can try from my end. Regarding exception - Is your URL (`http://JSON-DATA`) is correct? – Sanket Aug 16 '16 at 12:13
  • I tried also other type chart column, mix not only candlestick and still same exception. I also tried this sample http://www.knowstack.com/different-ways-of-loading-highcharts-data/ in my angular 2 app and I take JSON data and created data.json file from http://www.knowstack.com/webtech/charts_demo/data.json i get again EXCEPTION: Response with status: 200 Ok for URL: and also when i use knowstack adress in jsonp.request – Marko Aug 16 '16 at 12:25
  • @Marko check my EDIT answer. – Sanket Aug 16 '16 at 17:38
  • where ishould use your code? (in component or service) I am new in angular2, typescript and javascript. I just want create chart with my own data.json file which is on server or in folder with other angular2 files. – Marko Aug 17 '16 at 08:37
  • This is just for reference. Just check how I am setting chart options inside subscribe. I think you are missing this part. – Sanket Aug 17 '16 at 08:46
  • I get this error: XMLHttpRequest cannot load http://www.knowstack.com/webtech/charts_demo/data.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. Server error – Marko Aug 17 '16 at 08:59
  • that's because knowstack service is not enabled CORS on their side. – Sanket Aug 17 '16 at 09:25
  • can you help me with parse JSON data in angular2-highcharts? – Marko Aug 23 '16 at 11:25
  • How I wrote in second answer json data for example: http://www.knowstack.com/webtech/charts_demo/data.json source code my component is in previous answer. in this question – Marko Aug 23 '16 at 12:38
  • I would like create same chart like is this example ( http://www.knowstack.com/webtech/charts_demo/highchartsdemo4.html ) but in angular2 with angular2-highcharts. And i don't know how exactly parse data from json. – Marko Aug 25 '16 at 09:18
  • refer my EDIT 2 answer. This is how you can set options for column chart. I am not sure about your JSON format. – Sanket Aug 25 '16 at 09:41
  • thx this i tried but, i want use json file like http://www.knowstack.com/webtech/charts_demo/data.json so i need function which parse this json file like here http://www.knowstack.com/webtech/charts_demo/highchartsdemo4.html – Marko Aug 25 '16 at 10:42
  • @Marko check my EDIT 3 answer – Sanket Aug 31 '16 at 04:42
  • thx its work. But i have next question. What if i have this json data: var data = [{"key":"Math","value":98,"Mark":["Peter":"A","Michael":"C"]},{"key":"Physics","value":78,"Mark":["Peter":"B","Michael":"A"]}]; and i want use also data for Peter, Michael Marks. How can i do that? – Marko Sep 05 '16 at 07:25
  • If its work then mark as answer and raise new post for new question. – Sanket Sep 05 '16 at 07:42
1

Ok it is work. I use service which in my first post, I just changed 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;

in this case json data: [{"key":"Math","value":98},{"key":"Physics","value":78},{"key":"Biology","value":70},{"key":"Chemistry","value":90},{"key":"Literature","value":79}]

How can I split this data like there http://www.knowstack.com/webtech/charts_demo/highchartsdemo4.html

Marko
  • 227
  • 2
  • 6
  • 13