Whenever my backend sends a 404
error (indicating that the URL is valid, but the requested resource is not found, such as
http://localhost:4200/post/title-not-exist
), I need Angular to automatically redirect to my NotFoundComponent
without altering the URL visible in the browser.
The simplified code snippet is provided below:
constructor(private router: Router, private location: Location) {}
handleError(err: HttpErrorResponse) {
switch (err.status) {
case 404:
url = this.router.routerState.snapshot.url;
// '**' is set in the app-routing.module.ts
// { path: '**', component: NotFoundComponent }
this.router.navigate(['**'], { replaceUrl: false });
// Strange behavior observed here
// Without the setTimeout(), replaceState will not work
setTimeout(() => {
this.location.replaceState(url);
});
break;
default:
break;
}
return throwError(err);
}
Although I can successfully redirect to the NotFoundComponent
without changing the URL, there are some issues to address:
- My browsing history ends up showing redundant entries like:
/post/title-exist
→/post/not-exist
→/post/not-exist
when it ideally should be
/post/title-exist
→/post/not-exist
This also causes the back function to become stuck at a certain point. - If the
setTimeout()
is omitted,location.replaceState()
fails to update properly and the URL in the browser displays as/**
instead of reverting back to the previous snapshot URL.