使用 Angular2 处理 404

Handling 404 with Angular2

如果输入的路径无效,是否可以配置 Angular2 路由器重定向到特定路由?

例如,如果我有三个路线:
/家
/关于
/404

然后我输入 /trains(一条路线,路线配置中不存在),我希望路由器将我重定向到 404。

更新@angular/router

新路由器使用 '**' 路径规范可以更好地处理丢失的路由。

在您的根 RouterConfig 中,将组件添加为 catch-all 将在根级别和任何嵌套子级中捕获不正确的路由,这意味着您只需要在最顶层。以 ng2 英雄为例,如下所示:

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

根据 sharpmachine 的评论,确保所有 catch-all 路线都列在 其他路线 之后。当前路由器似乎基于 'first match'(express 风格)路由而不是 'specificity'(nginx 风格),尽管由于其不稳定程度,这可能会在未来改变。最后列出 catch-all 应该在这两种情况下都有效。


@angular/router 的原始答案-已弃用

我也找不到任何关于此的有用信息,也找不到什么可能是走向最终 ng2 版本的正确模式。不过在测试版中,我发现了以下作品。

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

我发现此代码也适用于子路由。即,如果您的 RouteConfig 中有 /cars/...,并且位置路径与您的任何子汽车路线都不匹配,您将收到父级指令的空值。这意味着您只需要在您的顶级主要组件中使用此代码。

不过,我希望将来有一种更简单、更明确的方法来做到这一点。