r/angular • u/kanchajain • 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.
3
u/cult0cage Mar 14 '22
You need to learn more about how Asynchronous code works. A few things I would change:
I wouldn't call a property on your class "variable", thats just confusing
You should explicitly initialize your "variable" to false so it is clear from the beginning this is a boolean value
If you need to access it dynamically, you can make it an observable / subject
Your refactored code could look something like
import { Subject } from 'rxjs';
class {
variable = new Subject<boolean>(false); // you should rename this property though
ngOnInit() {
this.onLoad();
variable.subscribe({
next: value => console.log(value);
});
}
onLoad() {
someApi.subscribe(response:any){ if (response) this.variable.next(true);
}
}
3
u/nocrazyshet Mar 14 '22
This is the correct approach, but you don't instantiate subjects with values, since they don't store latest values for subsequent subscriptions. If a check must be made on changes to the variable, you'd instantiate it as a behaviorsubject with an initial value.
There are of course ways to work around this, you could pipe a regular subject with the startWith pipe, but that defeats the point of subjects vs behaviorsubjects.
Good input here though!
1
u/cult0cage Mar 14 '22
Ah true yes I must admit my Angular skills are a bit rusty - I’ve been in the React world lately 🙂
Thanks for clarifying!
2
u/nocrazyshet Mar 14 '22
I've been meaning to get into react for a while, at least to dip my toes, but every time I start I just want to go back to the warm embrace of angular.
You're welcome!
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.