Highcharts angular 2 with observables http request

时间:2017-06-23 08:22:20

标签: angular typescript highcharts

我正在尝试创建一个使用来自http请求的observables的图表,以下代码正在处理一些假数据我只想用来自后端脚本的真实数据替换它们这里是我的代码:

我的app.ts:

export class MyVerticalchartComponent  {


   @Input() showMePartially: boolean;

  options: Object;

  constructor(public userService3: UserService3) {

       this.options = {
        title : { text : '' },
        chart: {  type: 'area' },
        legend: { enabled: false },
        credits: { enabled: false },
        xAxis: { type: 'datetime',
              //    startOnTick: true,
              //    endOnTick: true,
              //    tickInterval: 24 * 3600 * 1000,
            },
                  dateTimeLabelFormats: {
            second: '%H:%M:%S',
            minute: '%H:%M:%S',
            hour: '%H:%M:%S',
            day: '%H:%M:%S',
            week: '%H:%M:%S',
            month: '%H:%M:%S',
            year: '%H:%M:%S'
        },
        yAxis: { min: 0,
          max: 100 },
        plotOptions: {
          series: {
          //  pointStart: 0,
              color: '#648e59',
              fillOpacity: 0.8,
              fillColor: '#648e59'
                  }
        },
        series: [{
          name: 'Someone1',
          **data: [ // here should come my Observable !!
        [1497837618,0],[1497837738,0],[1497837858,0],[1497837978,0],[1497838098,0],[1497838218,0],[1497838338,0],[1497838458,0]    ],**
        }]
    };
}

}

我的app.html:

 <chart [options]="options">
      <series>
     </series>
  </chart>

我的http service.ts:

export interface User3 {
 data: any;
}
const usersURL = 'http://my.super.backend.script.com';

@Injectable() 导出类UserService3 {

users3:Observable;

constructor (public http: Http) {

          const tick3$ = Observable.timer(100, 60000);

      this.users3 = tick3$.flatMap(() => http.get(usersURL)).map(res => [res.json()]).publishBehavior(<User3[]>[]).refCount();

}
}

我的json看起来像:

  "operating_details":[[1497837618,0],[1497837738,0],[1497837858,0],
  [1497837978,0],[1497838098,0],[1497838218,0],[1497838338,0],
  [1497838458,0],[1497838578,0],[1497838698,0],[1497838818,0],
  [1497838938,0],[1497839058,0],[1497839178,0],[1497839298,0],
  [1497839418,0],[1497839538,0],[1497839658,0],[1497839778,0]]

1 个答案:

答案 0 :(得分:2)

我建议你将观察者移到单独的方法

getData() {
     const tick3$ = Observable.timer(100, 60000);

     return tick3$.flatMap(() => this.http.get(usersURL)).map(res => [res.json()]).publishBehavior(<User3[]>[]).refCount();

}

ngOnInit方法的组件中调用观察者

public ngOnInit () {
   this.userService3.getData().subscribe((data) => {
     console.log(this.options); // to see the strcture
     console.log(data); // to see the response

     this.options.series[0].data = data;
   });
}

被修改