基于API in Angular/ChartJS动态更新图(移动线图)
Dynamically updating graph(moving line graph) based on API in Angular/ChartJS
我正在尝试根据 API 调用实现移动线图(动态更新图),
但我遇到了错误。
图形的 x 轴应该是时间,y 轴应该是 stock_price.I 使用 Chart.js 图形和 Angular6。
应用组件
export class AppComponent {
chart = [];
ngOnInit(){
this._helper.helperHelp()
.subscribe(res => {
// console.log(res);
let times = [];
console.log(res);
let stock_price = res['stock_price'].map(res=>res.stock_price);
let timeloop = res['time'].map(res =>res.time);
//console.log(time);
timeloop.forEach((res) => {
times.push(times);
});
this.chart = new Chart('canvas',{
type: 'line',
data : {
labels : times,
datasets: [
{
data:stock_price,
borderColor: '#3cba9f',
fill: false
}
]
},
options:{
legend:{
display: false
},
scales: {
xAxis:[{
display:true
}],
yAxis:[{
display:true
}]
}
}
})
})
// console.log(this.timeSetter());
}
constructor(private _helper:HelperService){
setInterval(()=>{
this.ngOnInit(); },4000);
}
这是我从 json 文件中收到的内容
{
stock_price: 58,
time: "06:06:00am"
}
接下来
{
stock_price: 59,
time: "06:06:04am"
}
喜欢 API.
我认为问题在于我如何使用 map() 函数,但我仍然无法理解如何正确使用它。我在做这个的时候提到了这个tutorial。
必须在数组上调用 map
运算符。在您发布的控制台错误中, res
的值是单个对象。
由于您只能返回一个值,您可以:
将响应包装在一个数组中:
[{
stock_price: 59,
time: "06:06:04am"
}]
重构代码,这样就不需要使用地图了。我在想这样的事情可能会奏效。
let stock_price = res['stock_price'].stock_price;
我正在尝试根据 API 调用实现移动线图(动态更新图), 但我遇到了错误。
图形的 x 轴应该是时间,y 轴应该是 stock_price.I 使用 Chart.js 图形和 Angular6。
应用组件
export class AppComponent {
chart = [];
ngOnInit(){
this._helper.helperHelp()
.subscribe(res => {
// console.log(res);
let times = [];
console.log(res);
let stock_price = res['stock_price'].map(res=>res.stock_price);
let timeloop = res['time'].map(res =>res.time);
//console.log(time);
timeloop.forEach((res) => {
times.push(times);
});
this.chart = new Chart('canvas',{
type: 'line',
data : {
labels : times,
datasets: [
{
data:stock_price,
borderColor: '#3cba9f',
fill: false
}
]
},
options:{
legend:{
display: false
},
scales: {
xAxis:[{
display:true
}],
yAxis:[{
display:true
}]
}
}
})
})
// console.log(this.timeSetter());
}
constructor(private _helper:HelperService){
setInterval(()=>{
this.ngOnInit(); },4000);
}
这是我从 json 文件中收到的内容
{
stock_price: 58,
time: "06:06:00am"
}
接下来
{
stock_price: 59,
time: "06:06:04am"
}
喜欢 API.
我认为问题在于我如何使用 map() 函数,但我仍然无法理解如何正确使用它。我在做这个的时候提到了这个tutorial。
必须在数组上调用 map
运算符。在您发布的控制台错误中, res
的值是单个对象。
由于您只能返回一个值,您可以:
将响应包装在一个数组中:
[{ stock_price: 59, time: "06:06:04am" }]
重构代码,这样就不需要使用地图了。我在想这样的事情可能会奏效。
let stock_price = res['stock_price'].stock_price;