0

I am creating an Ionic application where I need to plot values in a Chart.js and save in an array the plotted values. The problem is that the declared array is returning as undefined inside the used function. I tried a lot of different kind of declarations and location, but it is not working. Below you can check my entire code. The first function that is triggered for this page is startBreath(). The variable that is undefined is this.capturedRRTime inside the function updateRR();

import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
import { Chart } from 'chart.js';

@Component({
  selector: 'app-training',
  templateUrl: './training.page.html',
  styleUrls: ['./training.page.scss'],
})
export class TrainingPage implements OnInit {

    @ViewChild('lineCanvas') lineCanvas : ElementRef;

    totalSeconds = 0;
    time_limit = 999999; //in seconds
    ctx:any;
    //canvas:any;
    hrv_chart:any;
    plotHRV:any;
    plotRR:any;
    min:any;
    max:any;
    circle_breath:any;
    capturedBPM:Array<any>;
    capturedBPMTime:Array<any>;
    capturedRRTime:Array<any>;

    config = {
      type: 'line',
      data: {
          labels: [],
            datasets: [{
              data: [],
              borderWidth: 1,
              borderColor:'#84C1D3'
            }]
      },
      options: {
        responsive: true,
        tooltips: {
            enabled: false
        },
        title: {
            display: false
        },
        legend: {
            display: false
        },
        elements: {
            point:{
                radius: 2
            }
        },
        scales: {
            yAxes: [{
                display: true,
                scaleLabel: {
                    display: true,
                    labelString: 'bpm'
                },
                ticks: {
                    max: 200,
                    min: 0,
                    stepSize: 20
                }
            }],
            xAxes: [{
                display: true,
                scaleLabel: {
                    display: true,
                    labelString: 'segundos'
                }
            }]
        }
      }
  }

  constructor() {}

  ngOnInit(){}

startBreath(){

    //var capturedRRTime: number[] = [];

    this.circle_breath = document.getElementById("circle_breath");

    if(this.circle_breath.style.animationName == "none"){
      this.circle_breath.style.animationName = "breath";
      this.createHRV();
      this.updateHRV();
    }

    if(this.circle_breath.style.webkitAnimationPlayState != "running"){
      this.circle_breath.style.webkitAnimationPlayState = "running";
      this.createHRV();
      this.updateHRV();
    }
}

stopBreath(){
  this.circle_breath = document.getElementById("circle_breath");
  this.circle_breath.style.animationName = "none";

  this.stopUpdateHRV();
  this.consolidateHRV();
}

getRandomIntInclusive(){
    this.min = Math.ceil(60);
    this.max = Math.floor(140);
    return Math.floor(Math.random() * (this.max - this.min + 1)) + this.min;
}

createHRV(){

    if(this.hrv_chart !== undefined && this.hrv_chart !== null){
        this.resetHRV();
        this.resetResume();
    }
    else{
        this.hrv_chart = new Chart(this.lineCanvas.nativeElement,this.config);
    }
}

resetResume(){
    //this.capturedRRTime = [];
    //this.capturedBPM = [];
    //this.capturedBPMTime = [];
    document.getElementById('bpm_atual').innerHTML = '0';
    document.getElementById('curr_rr_time').innerHTML = '0';
    document.getElementById('avg_rr_time').innerHTML = '0';
}

resetHRV(){
    this.totalSeconds = 0;
    this.stopUpdateHRV();
    this.hrv_chart.data.datasets[0].data = [];
    this.hrv_chart.data.labels = [];
    this.hrv_chart.update();
}

updateHRV(){

    this.updateRR();

    this.plotHRV = setInterval(function(){

        var maxXPoints = 60;
        var calculatedBPM = "";

        //console.log(this.hrv_chart);

        if(this.hrv_chart.data.labels.length > maxXPoints){
            this.hrv_chart.data.labels.shift();
            //removedXPoints.push(window.hrv_chart.data.datasets[0].data.slice(-1)[0]);
            this.hrv_chart.data.datasets[0].data.shift();
        }

        //TO-DO implement with real BPM - Sprint 3
        calculatedBPM = this.getRandomIntInclusive();

        this.capturedBPM.push(calculatedBPM);
        this.hrv_chart.data.datasets[0].data.push(calculatedBPM);
        document.getElementById('bpm_atual').innerHTML = calculatedBPM;

        var BPMTime = this.totalSeconds +=1;
        this.capturedBPMTime.push(BPMTime);
        this.hrv_chart.data.labels.push(BPMTime);

        this.hrv_chart.update();

        //stop the chart update
        if(this.totalSeconds === this.time_limit){
            clearInterval(this.plotHRV);
        }

    },1000);
}

updateRR(){
    var calculatedRRTime = 0;

    this.plotRR = setInterval(() => {
        //calculatedRRTime = this.getRandomFloat();
        calculatedRRTime = Math.floor(Math.random() * (1.1 - 0.6 + 1)) + 0.6;
        document.getElementById('curr_rr_time').innerHTML = calculatedRRTime.toString();

        console.log(this.capturedRRTime);

        this.capturedRRTime.push(calculatedRRTime);
    },600);
}

getRandomFloat(){
    this.min = 0.6;
    this.max = 1.1;
    return (Math.random() * (this.min - this.max) + this.max).toFixed(3);
}

avgArray(values){
    var sum = 0;
    var count = values.length;
    for (var i = 0; i < count; i++) {
        sum = sum + parseFloat(values[i]);
    }

    return (sum / count).toFixed(3);
}

stopUpdateHRV(){

    document.getElementById('avg_rr_time').innerHTML = this.avgArray(this.capturedRRTime);
    clearInterval(this.plotHRV);
    clearInterval(this.plotRR);
}

consolidateHRV(){
    this.hrv_chart.data.labels = (this.capturedBPMTime);
    this.hrv_chart.data.datasets[0].data = (this.capturedBPM);
    this.hrv_chart.update();
}

}
acg
  • 503
  • 3
  • 11
  • 27
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Aluan Haddad Oct 09 '19 at 07:50

1 Answers1

0

You have to use arrow function (=>) instead of function keyword inside of the function.

You need to change below code.

this.plotHRV = setInterval(() => {
...
...
});
Paresh Gami
  • 4,777
  • 5
  • 23
  • 41