Reputation: 1433
In my Ionic/Angular app I am converting some promised-based implementations to use observables instead. I am running into one issue with a particular function. My original (working, promised-based) code looked like this:
async getPlayerStats() {
this.user = await this.mainService.getPlayerStats(this.username);
this.checkRookieTopicCompletionStatus();
}
As you can see, with the above implantation I am waiting on this.user
before calling this.checkRookieTopicCompletionStatus();
That's important because I use this.user
in a for-loop
in that function.
Now, in my new observable-based implementation, my getPlayerStats()
function looks like this:
getPlayerStats() {
this.mainService.getPlayerStats(this.username).subscribe(
user => this.user = user,
error => this.errorMsg = error,
);
this.checkRookieTopicCompletionStatus();
}
The problem here is that this.checkRookieTopicCompletionStatus()
fires before this.user
is available. So my question is, how do I change this function above here so that I am assured I have this.user
data before this.checkRookieTopicCompletionStatus()
is called? Do I call it from somewhere within the subscribe()
block?
Upvotes: 0
Views: 25
Reputation: 1743
Do I call it from somewhere within the subscribe() block?
Yes, like so.
getPlayerStats() {
this.mainService.getPlayerStats(this.username).subscribe(
user => {
this.user = user;
this.checkRookieTopicCompletionStatus();
}
error => this.errorMsg = error,
);
}
Upvotes: 0
Reputation: 31125
Assuming this.mainService.getPlayerStats(this.username)
returns an observable, you need to include all the statements directly dependent on this observable inside the subscription. Try the following
getPlayerStats() {
this.mainService.getPlayerStats(this.username).subscribe(
user => {
this.user = user; // <-- this is assigned asynchronously
this.checkRookieTopicCompletionStatus();
},
error => this.errorMsg = error,
);
}
Upvotes: 1