Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling 404 with Angular2

Is there any way to configure Angular2 router to redirect to specific route, if invalid path is entered?

For example if I have three routes:
/home
/about
/404

and I enter /trains (a route, not present in route config), I'd like the router to redirect me to 404.

like image 271
Varnius Avatar asked Dec 11 '15 15:12

Varnius


People also ask

How to Show 404 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.

How do you intercept 404 errors angular 2?

The HTTP Interceptor service is used to handle the errors specific in Angular 2. The HTTP Interceptor service can be created and registered globally at the root module using the Angular Providers.

What is the purpose of wildcard route?

A Wildcard route has a path consisting of two asterisks (**). It matches every URL, the router will select this route if it can't match a route earlier in the configuration. A Wildcard Route can navigate to a custom component or can redirect to an existing route.


1 Answers

Update for new @angular/router

The new router handles missing routes much nicer with the '**' path specification.

In your root RouterConfig, adding a component as a catch-all will catch incorrect routes at the root level and within any nested children as well which means you only need to include it at the very top level. Taking the ng2 heroes example, this looks like the following:

export const routes:RouterConfig = [
  ...HeroesRoutes,
  { path: 'crisis-center', component: CrisisListComponent },
  // Show the 404 page for any routes that don't exist.
  { path: '**', component: Four04Component }
];

As per sharpmachine's comment, ensure that any catch-all routes are listed after any other routes. The current router appears to be based on 'first match' (express style) routing as opposed to 'specificity' (nginx style) although with its level of instability this might change in future. Listing catch-alls last should work under both conditions.


Original answer for @angular/router-deprecated

I haven't been able to find any good information on this either and what might be proper pattern moving towards the final ng2 release. In beta though, I've found the following works.

constructor(
  private _router: Router,
  private _location: Location
) {
  _router.recognize(_location.path()).then((instruction: Instruction) => {
    // If this location path is not recognised we receive a null Instruction
    if (!instruction) {
       // Look up the 404 route instruction
       _router.recognize('/404').then((instruction: Instruction) => {
         // And navigate to it using navigateByInstruction
         // 2nd param set to true to keep the page location (typical 404 behaviour)
         // or set to false to 'redirect' the user to the /404 page 
         _router.navigateByInstruction(instruction, true);
      });
    }
  });
}

I've found that this code will also work for child routes as well. i.e. If you have /cars/... within your RouteConfig and the location path doesn't match any of your child car routes, you will receive a null value for the instruction in the parent. This means you only need this code at your top level, main component.

I'm hoping there is an easier and more explicit way to do this in future though.

like image 127
Ian Belcher Avatar answered Oct 04 '22 14:10

Ian Belcher