javascript - 未捕获的类型错误 : Cannot read property 'addPoint' of undefined ( Highstock live data)

标签 javascript jquery highcharts

正如我发布的上一个问题,我正在使用 Highcharts 来使用具有 2 个系列(轴)的 REST API(Spring 应用程序)(http://85614a50.ngrok.io/api/devices)

第一个系列是内存 vs 时间,所以对象包含(内存使用,时间戳)。

第二个系列是CPU vs time,所以对象包含(CPU Usage, timestamp)。

enter image description here

这个数据现在是静态的,但我希望它是动态的。

我创建了一个函数,它每 5 秒调用一次 REST API,并在图表内创建一个事件函数,每 5 秒刷新一次。

我试图用系列在事件函数中声明变量,但它给了我这个错误:

Uncaught TypeError: Cannot read property 'addPoint' of undefined

代码笔示例:https://codepen.io/anon/pen/eLEyGb

首页.blade.php

@extends('index.app')

@section('main')
<style type="text/css">
  #container{
    width: 100%;
    margin: 0 auto;
  }

  .col-lg-4 {
    margin-bottom: 10%;
    min-width: 40%;
    max-width: 100%;
    margin: 1em auto;
    height: 400px;
  }
  .modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 10%; /* Location of the box */
    padding-right: 10%;
    padding-left: 10%;
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
  }  
  #container.modal{
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
    display:block;
  }
</style>

<h2 class="text-center" >{{$user->first_name}} Charts </h2>

<div id="container">
  <div class="row"></div>
</div>
<script type="text/javascript">
  $(function () {
      setInterval(getHighChart, 10000); //30 seconds onload="getHighChart()" 
  });

function getHighChart() {
  $.getJSON( "http://localhost:8000/api/devices", function( data ) {

console.log(data);

var mappedClientsAllias = _.map(_.uniqBy(data, "clientName"), "clientAllias");
var mappedClients = _.map(_.uniqBy(data, "Id_client"), "Id_client");

var devices= [];

_.forEach(mappedClients, function(Id_client, clientName) {
  var tempClient = {
    Allias: mappedClientsAllias[clientName],
    name: Id_client,
    data: [],
    memory:[]
  };
  tempClient2=tempClient;
  _.forEach(data, function(tempData) {
    if (clientId === tempData.clientId) {
      _.forEach(tempData.clientData, function(clientData) {
        tempClient.data.push([
          clientData.timestamp,
          clientData.cpuUsage,
        ]);
         tempClient.memory.push([
          clientData.timestamp,
          clientData.memoryUsage,
        ]);
      });
    }
  });

  devices.push(tempClient);
});

console.log("devices", devices);
var chart = _.forEach(devices, function(device) {

  $('<div class="col-lg-4">')
    .css("position", "relative")
    .appendTo("#container")
    .highcharts("StockChart", {
      marker: {
        states: {
          enabled: true
        }
      },
      time: {
        timezoneOffset: -5 * 60
      },
    exporting: {
      buttons: {
        customButton3: {
          text: 'Zooming',
          //make fullscreen of chart with size change
          onclick: function(b) {
             var w = $(window).width();
             var h = $(window).height();
          $(b.target).closest('#container').toggleClass('modal');
  if($(b.target).closest('#container').hasClass('modal')) {
    $('.col-lg-4').hide();
    $(b.target).closest('.col-lg-4').show();
    $('.col-lg-4').css({
      'width': w * .9,
      'height': h * .9
    });  
  } else {
    $('.col-lg-4').show();
     $('.col-lg-4').css({
                 'width': '',
                'height': ''

            });

  }
$(b.target).closest('.col-lg-4').highcharts().reflow();


                        }
                    }
                }
            }, 
      rangeSelector: {
        y: 15,
        buttons: [
          {
            count: 1,
            type: "minute",
            text: "Sec"
          },
          {
            count: 1,
            type: "hour",
            text: "Min"
          },
          {
            count: 1,
            type: "day",
            text: "Hours"
          },

          {
            type: "all",
            text: "All"
          }
        ],
        title: "hours",
        inputEnabled: true,
        _selected: 1
      },

      title: {
        text: device.Allias
      },
      yAxis: [{

                labels: {
                    enabled: true,
                    align: 'right',
                    x: -3
                },
                title: {
                    text: 'CPU'
                },
                height: '50%',
                lineWidth: 2,
                   color: 'red'
            }, {
                labels: {
                    align: 'right',
                    x: -3
                },
                title: {
                    text: 'Memory'
                },
                top: '70%',
                height: '50%',
                offset: 0,
                lineWidth: 2,

            }],
      xAxis: {
        tickInterval: 1,
        title: {
          enabled: true,
          text: "Client usage"
        },
         top: '20%',
        type: "datetime",
        dateTimeLabelFormats: {
          second: "%H:%M:%S",
          minute: "%H:%M",
          hour: "%H:%M",
          day: "%e. %b",
          week: "%e. %b",
          day: "%Y.%b-%d"
        }
      },

      plotOptions: {
        series: {
          marker: {
            enabled: false,
          }
        }
      },

       series: [{
        name: "Memory USAGE",
        data: device.memory.sort()
    },  // Add a new series
    {
        name: "Cpu USAGE",
         yAxis: 1,
          color: 'red',
        data: device.data.sort()

    }],
      chart: {
        renderTo: "container",
        height:400,
        events: {
          load: function () {
              // set up the updating of the chart each second
              var series = this.series[0];
              setInterval(function () {
                var x = (new Date()).getTime(), // current time
                y = Math.round(Math.random() * 100);
                series.addPoint([x, y], false, true);
              }, 1000);
            }
          }
        },
      });
    });
  });
}

</script>

@endsection

Layouts.app

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- CSRF Token -->
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Master thesis application</title>

  <!-- Jquery --> 
  <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

  <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

  <!-- Latest compiled and minified JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <link rel="stylesheet" type="text/css" href="https://getbootstrap.com/docs/3.3/examples/jumbotron-narrow/">
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

  <!-- Import css file-->
  <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>

  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script src="https://code.highcharts.com/stock/highstock.js"></script>
  <script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
</head>
<body>
  @include('file.hed')
  @include('file.bar')
  <script>
    window.onscroll = function() {myFunction()};

    var navbar = document.getElementById("navbar");
    var sticky = navbar.offsetTop;

    function myFunction() {
      if (window.pageYOffset >= sticky) {
        navbar.classList.add("sticky")
      } else {
        navbar.classList.remove("sticky");
      }
    }
  </script>

  <div class="container">
   @include('file.info')

  @yield('main')
  </div> <!-- /container -->

  @include('file.down')
</body>
</html>

最佳答案

由于这部​​分代码,您遇到了错误:

  events: {
        load: function (series) {
             var memory=client.memory.sort();

             setInterval(function () {
                 var x = memory;
                 series[0].addPoint([x], true, true);
            }, 5000);
        }
    }

您将 series 参数传递给事件函数,这实际上不是系列。这只是事件。如果要引用系列数组,请按以下方式操作:

  events: {
        load: function () {
             var memory = client.memory.sort(),
                 series = this.series;

             setInterval(function () {
                 var x = memory;
                 series[0].addPoint([x], true, true);
            }, 5000);
        }
    }

顺便说一句。我不太明白你为什么每 5 秒添加一次新图表,而不是更新旧图表。

实例: https://codepen.io/anon/pen/oPGYoZ

关于javascript - 未捕获的类型错误 : Cannot read property 'addPoint' of undefined ( Highstock live data),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52191240/

相关文章:

当 html 在 JSON 数据包中传递时,Javascript 错误

jquery - 根据窗口滚动条移动调整div位置

jquery - HighCharts 显示/隐藏数据点

javascript - 在 Eloquent Javascript 中循环

javascript - 如何在 Javascript 中将输出转换为矩阵

javascript - Ember js 1.12.0 - 无法创建实例

javascript - 使用 Turbolinks 的 Highcharts - Rails 4

javascript - 对数组进行 n 次过滤

Javascript 将 [url=] 转换为 html 链接

javascript - 显示 highchart 列范围图表 x 轴、y 轴和系列