I've found several articles here and on google discussing this but I just don't understand them. It seems that no matter where I place awaits and asyncs the code after my http.get call executes first. And the alert messages from the calling program after the point where I call my service doesn't show at all. I'm hoping someone can help me understand what I need to do in simple terms that a await/async newbie like me can understand. Thanks in advance for any help you can give.
The alerts that you see in the code appear on the page in this order:
single-game.component.ts: "first time in the single game component.....")
games.service.ts: "Do we get past the call/subscribe?"
games.service.ts: "Service --> current game is..." and on this one the alert does show the JSON that's returned.
Message 1 should appear first then message 3 then 2. And the ones in single-game.component.getCurrentGame that come behind the call to the service should appear after that.
single-game.component.ts code:
getCurrentGame() : void {
const id = Number(this.route.snapshot.paramMap.get('id'));
alert (`first time in the single game component and the value returned is ${this.currentGame?.Name}`)
this.gamesService.getCurrentGame(id).subscribe(value => this.currentGame = value);
// Neither of these two alerts ever show.
alert (`back in the single game component and the value returned is ${this.currentGame?.Name}`)
alert(`we're back but the above message didn't show`);
}
games-service.ts code
getCurrentGame(gameId: number): Observable<Game> {
game: GamesService;
var url:string = this.gamesURLBase + `/GetSingleGameInfo/${gameId}`;
var currentGame: Game |undefined;
var strCurrentGame: string;
this.http.get<Game[]>(url)
.subscribe((value:Game[]) => {
if (value.length > 0) {
currentGame = value.find(element => element.GameId == gameId)
alert(`Service --> currentGame is ${JSON.stringify(currentGame)}`)
};
})
alert("Do we get past the call/subscribe?")
return currentGame as unknown as Observable<Game>;
}
Thanks for taking the time to read this. And again, thanks in advance for any help you can give.