I am a beginner in the world of TypeScript and have been exploring ways to redirect users to an error page if the API response is not 200. Despite searching extensively online, I have yet to find a suitable solution. Here's what I currently have:
My service class contains basic HTTP methods like so:
PullDataFromServer(id: string): Observable<any> {
return this.http.get<string>(this.baseUrl + 'api/data/getdata?id=' + id, { observe: 'response' });
}
Within my component classes, I implement the following:
this.service.PullDataFromServer(this.userData.Id).subscribe({
next: data => {
this.data = data.body;
this.loaded = true;
},
error: err => {
this.router.navigate(['/errorpage']);
}
});
Despite my efforts, when the HTTP code is different from 200, my browser shows a prolonged server response time. I acknowledge that HTTP calls are asynchronous and cannot be made synchronous. My main concern lies in effectively managing user redirection upon encountering a server error.
While there are resources discussing asynchronous calls, I am grappling with error handling strategies. Any guidance on this matter would be greatly appreciated.
I've also made attempts using RxJS:
map(() => ''),
catchError((error: Error) => {
return this.router.navigate(['/errorpage']);
}));
Although async/await could be useful in scenarios where one call awaits another, how can it be leveraged for a single call awaiting a response?