【问题标题】:Handling 404 with Angular2使用 Angular2 处理 404
【发布时间】:2016-03-17 13:58:17
【问题描述】:

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

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

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

【问题讨论】:

    标签: typescript angular angular2-routing


    【解决方案1】:

    更新新的@angular/router

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

    在您的根 RouterConfig 中,添加一个组件作为包罗万象将在根级别以及任何嵌套子级中捕获不正确的路由,这意味着您只需要在最顶层包含它。以 ng2 hero 为例,如下所示:

    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 的评论,确保所有包罗万象的路线都列在 任何其他路线之后。当前路由器似乎基于“第一次匹配”(快速样式)路由,而不是“特异性”(nginx 样式),尽管由于其不稳定程度,将来可能会发生变化。在这两种情况下,最后列出包罗万象都应该有效。


    @angular/router-deprecated 的原始答案

    我也没有找到任何关于这方面的好信息,以及走向最终 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/... 并且位置路径与您的任何子汽车路线都不匹配,您将收到父指令中的空值。这意味着您只需要在顶层的主要组件中使用此代码。

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

    【讨论】:

    • 我认为您还必须添加 { path: '**', component: Four04Component } 作为最后一个路径。如果将其置于危机中心路径之上,那么您总是会被重定向到 404 页面。
    • 但是状态还是200,我怎么实际返回404状态呢?
    • 您只能从 http 请求中返回真正的 404,因此为给定路由返回 404 的唯一方法是使用通用服务器端渲染。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 2014-08-09
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多