未捕获的TypeError:无法读取未定义的属性“ addPoint”(Highstock实时数据)

时间:2018-09-05 18:17:12

标签: javascript jquery highcharts

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

第一个系列是内存与时间的关系,因此对象包含(内存使用情况,时间戳记)。

第二个系列是CPU与时间的关系,因此该对象包含(CPU使用率,时间戳记)。

enter image description here

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

我创建了一个函数,该函数每5秒调用一次REST API,并且Chart内部的事件函数每5秒刷新一次。

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

  

未捕获的TypeError:无法读取未定义的属性'addPoint'

电笔的示例:https://codepen.io/anon/pen/eLEyGb

Home.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>

1 个答案:

答案 0 :(得分:1)

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

  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