加载后ng2-highcharts图表更新

时间:2016-06-27 03:27:51

标签: highcharts angular firebase firebase-realtime-database rxjs

我正在使用angular 2,firebase和ng2-highcharts。

我从firebase收到数据之后分配数据,如下所示:

this.items = af.database.list('/items');
this.optionsAsync = this.items.map(data => {
    this.options.series[0].data = data.map(item => ([item.x, item.y]));
    return this.options;
});

然后在我的视图模板中我有:

<div [ng2-highcharts]="optionsAsync | async"></div>

首次加载时工作正常。但不幸的是,当收到新数据时,图表不会更新。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我通过引用带有@ViewChild的highcharts组件找到了一个解决方案,如下所示:

组件类中的

import { ViewChild, Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  directives: [Ng2Highcharts]
})
export class AppComponent {
  @ViewChild(Ng2Highcharts)
  chartElement: Ng2Highcharts;

  private chartData = {
        chart: {
            zoomType: 'x'
        },
        colors: ['rgba(255,0,255,1)'],
        title: {
            text: 'Items'
        },
        credits: '',
        series: [{
            type: 'area',
            name: 'Items',
            data: []
        }]
  };
  chartData$ = new Subject();

  ngOnInit() {
      this.items.subscribe((data: any) => {
        this.chartData.series[0].data = data.map(item => ([item.x, parseFloat(item.y)]) );
        this.chartData$.next(this.chartData);
        if(this.chartElement && this.chartElement.chart) {
          var serieRef = this.chartElement.chart.series[0];
          serieRef.setData(this.chartData.series[0].data);
        }
    });
  }
}