Angular 2如果路径不存在,如何重定向到404或其他路径[重复]

问题描述 投票:59回答:5

这个问题在这里已有答案:

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

我尝试研究有一些角度1但不是角度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/然后它工作,它返回一个空页面你如何处理这种情况发生?

javascript angular angular2-routing
5个回答
154
投票

对于v2.2.2及更高版本

在v2.2.2及更高版本中,name属性不再存在,不应用于定义路由。应该使用path而不是name,并且路径上不需要前导斜杠。在这种情况下使用path: '404'而不是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路径


25
投票

随着Angular继续发布,我遇到了同样的问题。根据2.1.0版,Route界面如下所示:

export interface Route {
    path?: string;
    pathMatch?: string;
    component?: Type<any>;
    redirectTo?: string;
    outlet?: string;
    canActivate?: any[];
    canActivateChild?: any[];
    canDeactivate?: any[];
    canLoad?: any[];
    data?: Data;
    resolve?: ResolveData;
    children?: Route[];
    loadChildren?: LoadChildren;
} 

所以我的解决方案如下:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '404', component: NotFoundComponent },
    { path: '**', redirectTo: '404' }
];

18
投票

我在2.0.0及更高版本上的首选选项是创建404路由,并允许**路径路径解析为同一个组件。这允许您记录和显示有关无效路由的更多信息,而不是可以用于隐藏错误的普通重定向。

简单404例子:

{ path '/', component: HomeComponent },
// All your other routes should come first    
{ path: '404', component: NotFoundComponent },
{ path: '**', component: NotFoundComponent }

要显示错误的路由信息​​,请将导入添加到NotFoundComponent中的路由器:

import { Router } from '@angular/router';

将它添加到Not Found Component的构造函数中:

constructor(public router: Router) { }

然后,您就可以从HTML模板中引用它,例如

The page <span style="font-style: italic">{{router.url}}</span> was not found.


9
投票

正如shaishab roy所说,在备忘单中你可以找到答案。

但在他的回答中,给出的答复是:

{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']}

由于某些原因,它不适合我,所以我尝试了:

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

它的工作原理。小心,不要忘记你需要把它放在最后,否则你将经常有404错误页面;)。


0
投票

确保使用这条404路由写在代码的底部。

语法就像

{
    path: 'page-not-found', 
    component: PagenotfoundComponent
},
{
    path: '**', 
    redirectTo: '/page-not-found'
},

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.