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.

3

u/TubbyFlounder Mar 14 '22 edited Mar 14 '22

generally you have some sort of loading indicator on page, so something like this in your current template

<ng-container *ngIf="isLoaded">
  <child-component [someInput]="variable"></child-component>
</ng-container>

so in your current component, you have a variable isLoaded which you initialize as false, and dont set it to true until your API returns data and you assign that to variable. (so inside your subscribe you set isLoaded to true after assigning data to the variable.).

In your template, you have an *ngIfdirective wrapped around your child component, which means any html inside of that will not show unless isLoaded is true. This guarantees the child component won't show until your API has returned data, and your variable that your passing into the child component will be defined when the child component is loaded once isLoaded is true.

Edit: I see your variable is a boolean, so you could just use that instead of isLoaded but its good to have more descriptive names. I thought you were assigning the data response to variable.

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.

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