When my backend sends me a 404
error (URL is valid, just because the resource is not found, like http://localhost:4200/post/title-not-exist
), I want Angular redirect to my NotFoundComponent
, without changing the URL in browser.
Code below (simplified):
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 });
// weird here too
// without the setTimeout(), replaceState will not work
setTimeout(() => {
this.location.replaceState(url);
});
break;
default:
break;
}
return throwError(err);
}
Now, I can redirect to NotFoundComponent
and the URL not changed, the problem is:
- My history will become things like:
/post/title-exist
→/post/not-exist
→/post/not-exist
which should be
/post/title-exist
→/post/not-exist
And the go back function will stuck here. - Without the
setTimeout()
,location.replaceState()
will not work, the URL in browser becomes/**
and not changing to the URL that snapshotted before.