Home > Net >  How to store in Angular fuction return value into variable
How to store in Angular fuction return value into variable

Time:10-21

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related