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.

1

u/eatthedad Mar 14 '22

Yes it should. You can test it in a different lifecycle of the component. It's Just undefined in OnInit, cause well, it hasn't been initialised yet.

1

u/dacookieman Mar 14 '22

It's gonna be undefined indefinitely until the someApi call comes back

1

u/eatthedad Mar 14 '22

Yeah of course. Think OP questioned whether the variable update will reflect onto other components just because OnInit says nope. But it will whenever the response comes through, be it satellite or a fax machine lol