简体   繁体   中英

How to store in Angular fuction return value into variable

I wanted to store the return value of an function into an variable. I tried this simple example.

drawChart(){
     var data = this.prepareData();
}

prepareData() {
    return 1;
}

But I got the error message:

Cannot read properties of undefined (reading 'prepareData')

Thank you for every help.

You have to call drawChart() method in ngOnInit() .

So this method gets call and you can get the return value from the prepareData() method

Here I'm attaching stackblitz url for your ref : stackblitz code

Hope that solve your problem.

You need to place drawChart() and prepareData() outside the ngInit(), constructor() and inside the component.

eg :

export class YourComponent implements OnInit {

   ngOnInit() {
     this.drawChart();
   }

   drawChart(){
       var data = this.prepareData();
    }

  prepareData() {
     return 1;
  }
 }

"this" keyword will point to the variables and functions inside the class, If you have declare these function inside a function, that won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM