简体   繁体   中英

Data fetched from api not showing in canvas.js plot

The given server code fetches the data but I don't know why it doesn't get assigned to yVal and the graph

输出图的快照

Below is the code for the server which fetches the data from API and send it back to the client

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);
})

Below is the client code where get() requests the server to fetch data from 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);

 }
}

It's likely that the data coming back from await get() is not just a number. It's a JSON representation of the value coming back. To see the format, do this:

  let yVal = await get();
  console.log(">>>yVal",yVal);

and see what's really coming back. If it's an object like { y: 7 } then you should be pushing the data like this:

dps.push({
  x: xVal,
  y: yVal.y
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM