Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  100] [ 4]  / answers: 1 / hits: 99505  / 6 Years ago, wed, june 20, 2018, 12:00:00

I am having an issue with my variables being undefined. I am certain this is because the observable hasn't finished. Here is the part of my code in my .ts file that is causing the issue. (I'm placing the minimum code required to understand the issue. Also myFunction gets called from a click event in the HTML).


export class myClass {
myVariable: any;

myFunction() {
this.myService.getApi().subscribe(data => {
this.myVariable = data;
});

console.log(myVariable) --> undefined
}
}

So this piece of code calls a function in my service that returns some data from an API. The issue is that when I try to access the variable myVariable right outside of the subscribe function it returns undefined. I'm sure this is because the subscribe hasn't finished before I try to access myVariable


Is there a way to wait for the subscribe to finish before I try to access myVariable?


More From » angular

 Answers
4

why not create a separate function and call it inside the subscription.



export class myClass {
myVariable: any;

myFunction() {
this.myService.getApi().subscribe(data => {
this.myVariable = data;
this.update()
});

this.update()
}

update(){
console.log(this.myVariable);
}
}

[#54160] Saturday, June 16, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nathalieg

Total Points: 462
Total Questions: 106
Total Answers: 93

Location: Turks and Caicos Islands
Member since Tue, Mar 30, 2021
3 Years ago
;