首页 > 解决方案 > 基于 Angular/ChartJS 中的 API 动态更新图形(移动线图)

问题描述

我正在尝试基于 API 调用实现移动线图(动态更新图),但出现错误。

在此处输入图像描述

图的 x 轴应该是时间,y 轴应该是 stock_price。我使用 Chart.js forgraphs 和 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() 函数,但我仍然无法理解如何正确使用它。我在做这个的时候参考了这个教程

标签: javascriptangularrestchartsangular6

解决方案


map必须在数组上调用操作符。在您发布的控制台错误中,值为res单个对象。

由于您只能获得一个值,因此您可以:

  1. 将响应包装在一个数组中:

    [{ stock_price: 59, time: "06:06:04am" }]

  2. 重构代码,这样您就不需要使用 map。我在想这样的事情可能会奏效。

    let stock_price = res['stock_price'].stock_price;


推荐阅读