angular - 我如何将在 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”提供给图形?
解决方案
考虑以下实现,其中数据更新在专用函数中执行,而该函数又在数据被解析后触发(在 内.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));
}
推荐阅读
- flutter - 如何布局彼此相邻但重叠的小部件
- stata - 在Stata中创建矩阵
- sql - 带有开始和停止的子句分区
- javascript - Vue.js 从外部 js 文件调用异步函数
- javascript - 是这个 w3schools javascript 示例的错误,还是我的错误?
- php - 从子关系 OOP Laravel 中获取父模型
- reactjs - 如何在反应中将单个字母与 onChange 事件分开?
- python - 无法使用 pythons SPARQLWrapper 从 GraphDB 中删除任何三元组
- javascript - 如何根据我的代码和 JSON 响应对象显示下拉菜单列表?
- python - 通过从列表中获取值,根据列值动态删除 Pandas 中的 DataFrame 行