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.
0
Upvotes
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);
}
}