Chartjs-(Angular Ionic) How can I stream my custom data with chartjs-plugin-streaming?

0👍

Let me answer my question for someone having same problem.

It works with the following code. Thanks.

  • I set options value in ngOnInit() function.
  • I used arrow function instead of function(){}.
import { Component } from '@angular/core';
import 'chartjs-plugin-streaming';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
export class Tab2Page {

  myDataFromServer:number=20;
  updateMyDataFromServerFunction:any;

  datasets: any[] = [{
    data: []
  }, {
    data: []
  }];

  options: any;
  constructor( ) {}

  ngOnInit(){

    this.options= {
      scales: {
        xAxes: [{
          type: 'realtime',
          realtime: {
            onRefresh: (chart: any) =>{
              chart.data.datasets.forEach((dataset: any) => {  
                dataset.data.push({
                  x: Date.now(),
                  y:this.myDataFromServer
                });
              });
            },
            delay: 2000
          }
        }],
        yAxes: [{
          ticks: {
            max:100,
            min:0
          }
        }]
      }
    };
    this.updateMyDataFromServer();
  }

  updateMyDataFromServer(){
    console.log('updateMyDataFromServer() called');    
    this.updateMyDataFromServerFunction = setInterval(() => {
      console.log('called');
      this.myDataFromServer = Math.random() * 100;
      console.log(this.myDataFromServer,'this.myDataFromServer');
    },1000)
  }
}

Leave a comment