打字稿 – 用角度处理404
有没有办法配置Angular2路由器重定向到特定的路由,如果输入无效的路径?
例如,如果我有三条路线: 我进入/列车(路线,路线配置中不存在),我希望路由器将我重定向到404.
新的@角/路由器的更新
新的路由器使用’**’路径规范处理丢失的路由更好. 在您的根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的评论,确保任何其他路线上列出所有的所有路线.目前的路由器似乎基于“第一匹配”(express style)路由,而不是“特异性”(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 / …,并且位置路径与您的任何小汽车路线不匹配,您将收到父项中的指令的空值.这意味着您只需要在顶层的主要组件的代码. 我希望今后有一个更容易和更明确的方式来做到这一点. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |