从api获取的数据未显示在canvas.js图中

问题描述 投票:0回答:1

给定的服务器代码获取数据,但是我不知道为什么不将其分配给yVal和图

snapshot of the output graph

下面是服务器的代码,该服务器从API提取数据并将其发送回给客户

const fetch = require("node-fetch");
const static = require('node-static');
const fileServer = new static.Server('.');
var express = require('express');
var app = express();

let url = "https://io.adafruit.com/api/v2/Drake_Sully/feeds/local-area1";

 app.listen(8081);
 app.use(express.static('./'))


app.get('/status', async (req,res)=>{
let response = await fetch(url);   
let data = await response.json();
res.send(data);
})

下面是客户端代码,其中get()请求服务器从api中获取数据

class Uploader {

constructor() {}

async plotLastValue(){

var dps = []; // dataPoints
var chart = new CanvasJS.Chart("plotLastValue", {
  title :{
    text: "Load vs Time Graph"
  },
   axisX:{
    title: "time in hour",
    gridDashType: "dot",
    gridThickness: 2
   },
  axisY: {
    includeZero: false,
    title: "Load in kW",
    customBreaks: [{
      startValue: 1,
      endValue: 50,
      interval: 10,  
      maximum : 5
    }]
  },      
  data: [{
    type: "line",
    dataPoints: dps
  }]
});

var xVal = 0;
var yVal = 0; 
var updateInterval = 1000;
var dataLength = 20; // number of dataPoints visible at any point

async function get() {  // function to fetch data 
  let response = await fetch('status');
  let res = await response.json();
  return res["last_value"]; 
}


var updateChart = async function (count) {

  count = count || 1;

  for (var j = 0; j < count; j++) {
    let yVal = await get();
    dps.push({
      x: xVal,
      y: yVal
    });
    xVal++;
  }

  if (dps.length > dataLength) {
    dps.shift();
  }

  chart.render();
};

updateChart(dataLength);
setInterval(function(){updateChart()}, updateInterval);

 }
}
javascript node.js fetch canvasjs
1个回答
0
投票
您永远不会在dps中设置新的canvas数据。在chart.render()调用之前尝试以下操作:

chart.options.data[0].dataPoints = dps; chart.render();

因为它可能需要复制初始点(空),并且不知道您的本地数组已更改。
© www.soinside.com 2019 - 2024. All rights reserved.