2016-08-16 2 views
2

Я хочу создать диаграмму на основе данных JSON. я с помощью angular2-Highcharts мой ChartsMain компонент выглядит следующим образом:Данные JSON с угловыми2-high-диаграммами

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

И мой DataService выглядит:

@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

Где проблема, почему график пустой? Как заполнить диаграмму данными JSON. Данные JSON должны быть в любом конкретном формате?

+1

вы можете обмениваться данными в формате JSON? – Sanket

+0

Да, мои данные JSON: [ \t { \t \t Id: 1, \t \t Name: "Name1", \t \t ProductId: 2, \t \t ProductName: "ProductName1", \t \t StartMonth: "2016-01-01T00:00:00", \t \t EndMonth: "2016-01-01T00:00:00", \t \t Number1: 1, \t \t Number2: 2, \t \t ProductDetail: [ \t \t \t { \t \t \t \t Id: 101, \t \t \t \t OrderId: 1001, \t \t \t \t ProductionMonth: "2016-01-01T00:00:00", \t \t \t \t OrdersCount: 10, \t \t \t \t StorageCount: 1, \t \t \t \t ProductAll: null \t \t \t } \t \t ] \t }, ] Marko

ответ

3

Подсвечник диаграмма обычно используется для представления открытой, высокий, низкий и цена закрытия в течение определенного периода времени ..

Sample ожидается формат JSON выглядит 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], 
] 

Вот пример компонент с подсвечником 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 
        } 
       }] 
      }; 

     }); 
} 

РЕДАКТИРОВАТЬ:

В вашем случае вы не устанавливаете параметры диаграммы внутри подписки. Вы должны установить, как 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 
       }); 

Пожалуйста, обратите внимание - данные из knowstack будет работать только с простыми графиками (не свечных)


EDIT 2: Гистограмма

Пожалуйста, обратитесь ниже конфигурации. Вот как вы можете использовать столбчатую диаграмму.

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

РЕДАКТИРОВАТЬ 3: образец ключ-значение пары 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; 
} 
+0

Так что я не могу использовать другой формат json? Когда я использую образец компонента и даю url для своего json, я получаю следующее: ИСКЛЮЧЕНИЕ: Ответ со статусом: 200 Ok для URL: – Marko

+0

Я не думаю, что свеча придерживается другого формата json. можете ли вы поделиться своими данными JSON? Я могу попытаться с моей стороны. Что касается исключения - правильный ли ваш URL ('http: // JSON-DATA')? – Sanket

+0

Я пробовал и другие колонки диаграммы типа, смешивать не только подсвечник, но и все те же исключения. Я также попробовал этот образец http: //www.knowstack.com/different-ways-of-load-highcharts-data/в моем угловом приложении 2, и я беру данные JSON и создаю файл data.json с http://www.knowstack.com/webtech/charts_demo/data.json, я получаю снова ИСКЛЮЧЕНИЕ: Ответ со статусом: 200 Ok для URL: а также когда я использую адрес notstack в jsonp.request – Marko

1

Ok это работа. Я использую сервис, который в своем первом посте я просто изменил компонент: 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;

в этом случае JSon данные: [{"key":"Math","value":98},{"key":"Physics","value":78},{"key":"Biology","value":70},{"key":"Chemistry","value":90},{"key":"Literature","value":79}]

Как я могу разделить эти данные, как там http://www.knowstack.com/webtech/charts_demo/highchartsdemo4.html

 Смежные вопросы

  • Нет связанных вопросов^_^