将数据从界面获取到具有Angular 5的Highcharts图表



我正在使用此NPM软件包制作图表:https://www.npmjs.com/package/angular-highcharts

我有一个接口,我想从接口中取值以填充图表。在这个阶段,我想要的是线图。

我尝试了各种使用数组来执行此操作的方法,只要我通过硬编码其正常工作的所有值来初始化数组,但我想将服务值从服务中动态加载到接口中,然后取从接口到图表的值。我在做什么错?

这是我的component.ts

import { Component, OnInit } from '@angular/core';
import { Chart } from 'angular-highcharts';
import { WeatherstatsService } from '../weatherstats.service';
import 'rxjs/add/operator/map';
interface WeatherData {
  id: any;
  year: any;
  measurement_type: string;
  location: string;
  month_or_season: string;
  value?: any;
}
let datavalues: WeatherData [] = [];
@Component({
  selector: 'weatherchart',
  templateUrl: './weatherchart.component.html',
  styleUrls: ['./weatherchart.component.css']
})
export class WeatherchartComponent implements OnInit {
  constructor(private weatherstatsservice: WeatherstatsService) { }

  title = "Title";
  data: any;
  datavalues = datavalues;
  values: Array<number> = [];

  chart = new Chart({
        chart: {
          type: 'line'
        },
        title: {
          text: this.title,
        },
        credits: {
          enabled: false
        },
        series: [{
          name: 'Line 1',
          data: this.datavalues.year,
        }]
      });
    // add point to chart serie
    add() {
      this.chart.addPoint(Math.floor(Math.random() * 10));
    }
    ngOnInit() {
          this.weatherstatsservice.getWeatherData()
            .subscribe(data => {
              this.data = data.slice(0, 100);
             if(this.data){
              this.data.forEach( res => {
                this.datavalues.push({
                  id: res.id,
                  year: res.year,
                  measurement_type: res.measurement_type,
                  location: res.location,
                  month_or_season: res.month_or_season,
                  value: res.value,
                })
               });
               console.log(this.datavalues);
            }
        })
      }

    }

这是图书馆的常见问题,我在NG2-charts上遇到了同样的问题,可以使用API进行Redraw IT解决。

您可以通过将图表的实例作为

进行
<chart [options]="options" (load)="saveInstance($event.context)"></chart>

和ts

chart: Object;
saveInstance(chartInstance): void {
     this.chart = chartInstance;
}

,当您从API获取数据时,您可以用作

重新绘制
updateSeries(data: Array<any>): void {
   this.chart.series[0].setData(data);
}

最新更新