I've been reading various articles and forums, both here and on Google, about using awaits and asyncs in my code. However, no matter where I place them, the code after my http.get call always executes first. The alert messages from the calling program also don't show up after I call my service. Can someone please explain to me in simple terms what I need to do? I'm new to await/async and would appreciate any help you can provide.
The order of alerts appearing on the page is as follows:
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..." The alert shows the returned JSON.
Message 1 should appear first, followed by message 3, and then message 2. The alerts in single-game.component.getCurrentGame that come after calling the service should appear next.
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>;
}
Thank you for taking the time to read this. I appreciate any insights or guidance you can offer.