首页 > 解决方案 > Chart.js:在 onRefresh() 方法之外调用方法

问题描述

我附上了代码片段。我在 HomeComponent 类中有一个方法,rand()我想为 y 轴调用它,但从目前的情况来看,这是不可能的,因为每当onRefresh()被调用时this.rand()都无法访问,这是预期的。因为onRefresh()从核心库 core.js 调用。所以请帮助完成这项工作

export class HomeComponent implements OnInit, OnDestroy {
....
..
options: any = {
    scales: {
      xAxes: [
        {
          type: 'realtime',

          realtime: {
            onRefresh(chart: any) {


              chart.data.datasets.forEach(function(dataset: any) {
                dataset.data.push({
                  x: Date.now(),

                  **y: this.rand()**
                });
              });
              chart.config.options.scales.yAxes[0].ticks.min = chart.helpers.niceNum(20);
              chart.config.options.scales.yAxes[0].ticks.max = chart.helpers.niceNum(180);
            },

            delay: 2000
          }
        }
      ]
    },
    annotation: {
      annotations: [
        {
          type: 'line',
          mode: 'horizontal',
          scaleID: 'y-axis-0',
          value: '120',
          borderColor: 'tomato',
          borderWidth: 2
        },
        {
          type: 'line',
          mode: 'horizontal',
          scaleID: 'y-axis-0',
          value: '70',
          borderColor: 'blue',
          borderWidth: 2
        }
      ]
      //drawTime: "afterDraw" // (default)
    }
  };
  ....
  ....
  
  rand(): Number {
    return Math.floor(Math.random() * (200 - 100 + 1)) + 100;
  }
  }

提前致谢 :)

标签: javascriptangularjschart.js

解决方案


鉴于您的实现rand,仅对 X 轴数据执行您正在执行的操作还不够吗?

IE

                dataset.data.push({
                  x: Date.now(),
                  y: Math.floor(Math.random() * (200 - 100 + 1)) + 100;
                });

推荐阅读