Say I have an route with a param like this (in Angular 2): /user1/products/:id
, which could have child routes like /user1/products/3/reviews
.
When I navigate to /user1/products/-1
, I check with my server and if the product doesn't exist, I want to render a 404 page without affecting the browser history.
Using router.navigate(['/404'])
or router.navigateByUrl('/404')
doesn't seem to work because it adds both /user1/products/-1
and/404
to the browser history.
Meaning when I press the Back button in the browser, I go back to /user1/products/-1
which is immediately redirected to /404
and I'm essentially stuck at /404
.
In ExpressJS, we would do something like next()
to pass the request to our 404 handler. Is there a client-side equivalent in Angular 2?
To fix the 404 error, you need to update your server to serve the index. html file for each route path you defined.
To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple angular component called PagenotfoundComponent. Creating Component: Run the below command to create pagenotfound component.
To switch to HashLocationStrategy, use this code: imports: [ ... RouterModule. forRoot(routes, { useHash: true }), ... ]
As of Angular 2 final this is the solution:
this._router.navigateByUrl('/404', { skipLocationChange: true })
Ok, this is already implemented, just not well-documented.
According to the docs:router.navigateByUrl(url: string, _skipLocationChange?: boolean) : Promise<any>
Has a parameter _skipLocationChange that will not modify the history.
These will do the trick:
router.navigateByUrl('/404', true);
router.navigateByInstruction(router.generate(['/404']), true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With