ERROR TypeError: Cannot read property 'testMethod' of undefined

余生长醉 提交于 2021-01-29 08:50:58

问题


I have following code for component.ts

export class HomeComponent implements OnInit {
  Linecap = {};
  dataArray=[];

  constructor(private chartGetDataService: ChartGetDataService) {
 }

  ngOnInit(): void {
         this.chartPlotting();
  }


public testMethod(){
  this.chartGetDataService.getLatestData1().subscribe( list=>{ this.dataArray=list.map(item=>{return item.payload.val()});} );
  console.log(this.dataArray);
  return this.dataArray;
 }

public chartPlotting(){

  this.Linecap= new Chart('canvas',
  {
   type: 'line',
   data: { labels: [moment().toDate().getTime()], datasets: [{ label:'Flow',yAxisID: 'A',lineTension: 0, data: [] , borderColor: '#3cb371', fill: false ,borderWidth:2},
                                                            ]
         },
   options: { responsive: true,animation: {duration: 0},hover: {animationDuration: 0},responsiveAnimationDuration: 0,
              scales: { xAxes: [{ type: 'realtime',time: { parser: undefined} , display: true }],
                        yAxes: [{ id:'A', display: true, ticks: { beginAtZero: true, fontColor:'#f4af07',  stepSize: 10, max: 100}},
                                ]
                      },

              plugins: {  streaming: {
                      duration: 60000,
                      refresh: 2000,
                      delay: 3000,
                      pause: false,
                      ttl: undefined,
                      frameRate: 2,
                      onRefresh: function(Linecap) {

                        console.log(this.testMethod())
                        console.log(this.dataArray)

                                                                        Linecap.data.datasets[0].data.push({x: Date.now(), y: this.dataArray[2] });
                        Linecap.update({ preservation: true });
                        }

                    }
},

}

})

}

I am stuck with 2 problems in this code.

  1. My first console.log in testMethod() returns desired value that means method is working fine and values are stored in dataArray but when I try to read dataArray inside onRefresh Linecap.data.datasets[0].data.push({x: Date.now(), y: this.dataArray[2] }); function it gives me error ERROR TypeError: Cannot read property 'dataArray' of undefined
  2. If I call testMethod in onRefresh function like var ws=this.testMethod() it gives me error ERROR TypeError: Cannot read property 'testMethod' of undefined. Subsequent call of console.log(this.testMethod()) is also throwing same error

What wrong I am doing? I am not able to find it. How do I solve undefined error for this code. If I call testMethod outside onRefresh function it works perfectly but it returns empty dataArray.


回答1:


Meaning of this keyword in a Javascript function depends on the usage. See here for more details.

Either way it will not refer to the scope of the class. To refer to the scope of the class using the this keyword, use arrow function expression. Try the following

plugins: {  
    .
    .
    .
    onRefresh: (Linecap) => {
      console.log(this.testMethod())
      console.log(this.dataArray)
      Linecap.data.datasets[0].data.push({x: Date.now(), y: this.dataArray[2] });
      Linecap.update({ preservation: true });
    }
  }
}



回答2:


The scope inside the onRefresh function is different than the component scope so this is undefined use instead an arrow function for the onRefresh like this

onRefresh: (Linecap)  => { ... }


来源:https://stackoverflow.com/questions/61551420/error-typeerror-cannot-read-property-testmethod-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!