首页 > 解决方案 > 我如何将在 ngOnInti() 中获得的数组传递给该函数之外的图形?

问题描述

客观的:

我的目标是从通过 API 拉入并调用然后进行重组的数据中创建一个图表。调用发生在 ngOnInit() 中,而绘图发生在它的外部。我无法获取拉入、推入图表的数据:

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {StockServicesComponent} from '../services/stock-services.component';
import * as Highcharts from 'highcharts/highstock';
import { Options } from 'highcharts/highstock';

@Component({
  selector: 'app-high-charts',
  templateUrl: './high-charts.component.html',
  styleUrls: ['./high-charts.component.css']
})
export class HighChartsComponent implements OnInit {

  constructor( private route: ActivatedRoute,
               private service: StockServicesComponent) { }

  stockPrices = [];
  dates = [];
  prices = [];
  newDataset = [];

  Highcharts: typeof Highcharts = Highcharts;
  chartOptions: Options = {
    series: [
      {
        type: 'line',
        pointInterval: 24 * 3600 * 1000,
        data : this.newDataset
      }
    ]
  };

  ngOnInit(): void {
    this.route.params.subscribe(params => {
      const tickerId = params.tickerId;
      this.service.findCompanyPriceHistory(tickerId)
        .then(stockPrices => this.stockPrices = stockPrices);
      console.log('Reached Highcharts 1: ', this.newDataset);

      this.stockPrices.forEach(obj => {
        const tmp = [];
        tmp.push(obj.updated);
        tmp.push(obj.close);
        this.newDataset.push(tmp);
        console.log('----------------');
      });
      console.log('Reached Highcharts 2: ', this.newDataset);
    });
  }
}

问题:

如何按照“数据:this.newDataset”的规定将“newDataset”提供给图形?

标签: angulartypescripthighcharts

解决方案


考虑以下实现,其中数据更新在专用函数中执行,而该函数又在数据被解析后触发(在 内.then):

public updateDataSet(stockPrices: any[]):void {
  stockPrices.forEach(obj => {
    const tmp = [];
    tmp.push(obj.updated);
    tmp.push(obj.close);
    this.newDataset.push(tmp);
  });
}

ngOnInit(): void {
  this.route.params.subscribe(params => {
    this.service
      .findCompanyPriceHistory(params.tickerId)
      .then(stockPrices => this.updateDataSet(stockPrices));
  });
}

或者更简洁:

ngOnInit(): void {
  this.route.params
    .pipe(
      switchMap(x => this.service.findCompanyPriceHistory(x.tickerId))
    )
    .subscribe(stockPrices => this.updateDataSet(stockPrices));
}

推荐阅读