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?

2
  • 1
    can you share your JSON data? Commented Aug 16, 2016 at 10:17
  • yes, my JSON data are: <code> [ { 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 } ] }, ]</code> Commented Aug 16, 2016 at 12:12

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

16 Comments

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:
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?
I tried also other type chart column, mix not only candlestick and still same exception. I also tried this sample knowstack.com/different-ways-of-loading-highcharts-data in my angular 2 app and I take JSON data and created data.json file from 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 check my EDIT answer.
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.
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.