Angular 2 如果路径不存在,如何重定向到 404 或其他路径 [英] Angular 2 How to redirect to 404 or other path if the path does not exist

查看:41
本文介绍了Angular 2 如果路径不存在,如何重定向到 404 或其他路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 angular 2 中不存在路径,我试图重定向 404 / 其他路径

I was trying to redirect 404 / other path if the path does not exist in angular 2

我试过研究有一些方法可以用于角度 1 而不是角度 2.

I tried research there is some method for angular 1 but not angular 2.

这是我的代码:

@RouteConfig([
{
    path: '/news',
    name: 'HackerList',
    component: HackerListComponent,
    useAsDefault: true
},
{
    path: '/news/page/:page',
    name: 'TopStoriesPage',
    component: HackerListComponent
},
{
    path: '/comments/:id',
    name: 'CommentPage',
    component: HackerCommentComponent
}
])

例如,如果我重定向到 /news/page/ 然后它可以工作并且它返回一个空页面你如何处理这种情况发生?

So example if I redirect to /news/page/ then it works and it return me an empty page how do you handle this kind of case happen?

推荐答案

适用于 v2.2.2 及更新版本

在 v2.2.2 及更高版本中,name 属性不再存在,不应用于定义路由.应该使用 path 而不是 name 并且路径上不需要前导斜线.在这种情况下,使用 path: '404' 而不是 path: '/404':

In version v2.2.2 and up, name property no longer exists and it shouldn't be used to define the route. path should be used instead of name and no leading slash is needed on the path. In this case use path: '404' instead of path: '/404':

 {path: '404', component: NotFoundComponent},
 {path: '**', redirectTo: '/404'}

对于早于 v2.2.2 的版本

你可以使用 {path: '/*path', redirectTo: ['redirectPathName']}:

{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},

{path: '/*path', redirectTo: ['NotFound']}

如果没有路径匹配则重定向到 NotFound 路径

if no path matches then redirect to NotFound path

这篇关于Angular 2 如果路径不存在,如何重定向到 404 或其他路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆