Var*_*ius 22 typescript angular2-routing angular
如果输入了无效路径,有没有办法配置Angular2路由器重定向到特定路由?
例如,如果我有三条路线:
/ home
/ about
/ 404
我输入/训练(路线,路线配置中不存在),我希望路由器将我重定向到404.
Ian*_*her 36
新路由器使用'**'
路径规范处理丢失的路由更好.
在您的根目录中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 }
];
Run Code Online (Sandbox Code Playgroud)
根据sharpmachine的评论,确保在任何其他路线之后列出任何包罗万象的路线.当前路由器似乎基于"第一次匹配"(快速样式)路由而不是"特殊性"(nginx样式),尽管其不稳定程度可能在将来发生变化.列表catch-alls last应该在两种条件下都能工作.
我无法找到任何关于此的任何好的信息,以及可能正在向最终的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);
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
我发现这段代码也适用于子路由.即如果您/cars/...
在RouteConfig中并且位置路径与您的任何子车路线都不匹配,您将在父级中获得指令的空值.这意味着您只需要在顶级主要组件中使用此代码.
我希望将来有更简单,更明确的方式来做到这一点.
归档时间: |
|
查看次数: |
7371 次 |
最近记录: |