Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 resolve guard redirect without changing URL?

I want to display a 404 page/component if my resolve guard fails, but I do not want the URL of the browser to change.

I can navigate without changing the URL in the resolve as described here by doing:

this.router.navigate(['/404'], { skipLocationChange: true })

This works when getting to this guard from within the app. However, if I navigate directly to the page, ex: /posts/1234 the router changes the URL to the fallback route (thought the 404 component is correctly displayed). If I do not skip location change, everything works as expected, but then I have '/404' in my url which I do not want.

Is there a way to achieve this with the router currently, or is it a bug?

like image 411
tam5 Avatar asked Oct 26 '25 22:10

tam5


1 Answers

I'm facing the same problem. In the unlikely event you still want to solve this, I found this Github issue: https://github.com/angular/angular/issues/16981

Does't seem like there is a legit way to handle this, but there is a good workaround suggested by Karolis92

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):     Observable<boolean> {
   <...>
   this.router.navigate(['404']);
   setTimeout(() => this.location.replaceState(state.url));
   <...>
}
like image 125
user3370237 Avatar answered Oct 29 '25 15:10

user3370237



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!