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

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

问题描述

如果该路径在角度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及更高版本中,名称属性不再存在,并且不应用于定义路由.应该使用 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天全站免登陆