Hoàng Nguyễn
Hoàng Nguyễn

Reputation: 1182

Angular-highcharts pushing data from api into highchart option

I got following data (https://api.coindesk.com/v1/bpi/historical/close.json):

{
   bpi: {
   2017-12-15: 17601.9438,
   2017-12-16: 19343.04,
   2017-12-17: 19086.6438,
   2017-12-18: 18960.5225,
   ...
}

I use this library to visualize my line chart: https://github.com/cebor/angular-highcharts

I tried to push the above data into the highcharts option, but nothing showed up without any errors. Therefore, I doubt my pushing method that needs someone give advice.

Here is the code:

export class ChartComponent implements OnInit {

  stockChart: StockChart;
  historyData = [];

  constructor(private apiService: ApiService) {
    this.apiService.getBtcData()
    .subscribe((data) => {
      this.historyData = Object.values(data.bpi);
      console.log(this.historyData);
    });
   }

  ngOnInit() {
    this.stockChart = new StockChart({
       series: [{
          tooltip: {
            valueDecimals: 2
          },
          marker: {
            enabled: false
          },
          name: 'BTC/USD',
          data: this.historyData
        }]
    }) 
  }
}

Upvotes: 0

Views: 1030

Answers (1)

LLai
LLai

Reputation: 13416

historyData is not defined when you are initializing the chart data in your ngOnInit, so your chart has no data. You should instead initialize your chart within your subscribe (after historyData is defined)

this.apiService.getBtcData()
    .subscribe((data) => {
        this.historyData = Object.values(data.bpi);

        this.stockChart = new StockChart(...);
    });

or set the data through the highcharts setData method and redraw the chart

this.apiService.getBtcData()
    .subscribe((data) => {
        this.historyData = Object.values(data.bpi);
        // assign chart data and redraw (2nd parameter of setData)
        this.stockChart.ref.series[0].setData(this.historyData, true);
    });

Upvotes: 3

Related Questions