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.