Handling 404 with Angular2

2019-02-08 02:25发布

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.

1条回答
ら.Afraid
2楼-- · 2019-02-08 02:51

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.

查看更多
登录 后发表回答