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

Angular 2 How to redirect to 404 or other path if the path does not exist

如果 angular 2

中不存在该路径,我试图重定向 404 / 其他路径

我试过研究 angular 1 但不是 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/ 那么它就可以工作并且它 return 我是一个空白页面 你如何处理这种情况发生?

对于 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 路径

正如 shaishab roy 所说,在秘籍中 sheet 你可以找到答案。

但在他的回答中,给定的回应是:

{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 错误页面 ;)。

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

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

我在 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';

将其添加到 NotFoundComponent 的构造函数中:

constructor(public router: Router) { }

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

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

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

语法类似于

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

谢谢