Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 route to 404 page when route param is invalid

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?

like image 203
Simonxca Avatar asked Apr 13 '16 13:04

Simonxca


People also ask

How to fix 404 error in angular?

To fix the 404 error, you need to update your server to serve the index. html file for each route path you defined.

How to 404 error page in angular?

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.

Which of the below code is used to import Hashlocation strategy?

To switch to HashLocationStrategy, use this code: imports: [ ... RouterModule. forRoot(routes, { useHash: true }), ... ]


2 Answers

As of Angular 2 final this is the solution:

this._router.navigateByUrl('/404', { skipLocationChange: true })
like image 130
AT82 Avatar answered Sep 21 '22 14:09

AT82


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);

like image 20
Simonxca Avatar answered Sep 18 '22 14:09

Simonxca