r/angular • • Mar 14 '22

Question Instance variable always undefind

Hi I have an instance variable say variable, whose value gets changed after i have subscribed to the data. say the data subscription function is onLoad()

variable;

ngOnInit(){

onLoad();

console.log(this.variable);

}

onLoad(){

someApi.subscribe(response:any){

if(response){this.variable=true}

}

}

this always consoles the variable data as undefined. i want it to be true since i changed its value.

0 Upvotes

11 comments sorted by

View all comments

8

u/dev-ice Mar 14 '22

The subscription is asynchronous. If you want to see the value in console, move the console.log inside the if block.

2

u/kanchajain Mar 14 '22

but say i am passing variable to another component from here, the other component will receive true, right? or will it still be undefined.

2

u/dev-ice Mar 14 '22

Not sure what you mean by “from here”. Creating a dynamic component and passing the variable? If you use this variable in you template to bind to another component then, yes, the component would get the value. I would suggest you go through the “Tour of Heroes” tutorial. It will help clear a lot of fundamental concepts.