Angular 重定向错误4045
当URL错误时,我试图处理404错误。这是我的登录url,如果我写了类似http:…/loginasdasd的东西,我想自动打开我自己的NotFoundPage。Angular 重定向错误4045,angular,http-status-code-404,Angular,Http Status Code 404,当URL错误时,我试图处理404错误。这是我的登录url,如果我写了类似http:…/loginasdasd的东西,我想自动打开我自己的NotFoundPage。 const批准3:路由=[ { 路径:“”, 儿童:[ { 路径:“登录”, 组件:登录页面 }, {路径:'login**',重定向到:'/notfound'} ] }, {路径:'notfound',组件:NotFoundPage} ]; RouterModule.forRoot( 批准3, {enableTracing:tru
const批准3:路由=[
{
路径:“”,
儿童:[
{
路径:“登录”,
组件:登录页面
},
{路径:'login**',重定向到:'/notfound'}
]
},
{路径:'notfound',组件:NotFoundPage}
];
RouterModule.forRoot(
批准3,
{enableTracing:true}/因为Angular尝试按照您在routes数组中声明的顺序匹配路由。您可以执行以下操作:
const appRoutes3: Routes = [
{
path: '',
children: [
{
path: 'login',
component: LoginPage
}
},
{ path: '**', component: NotFoundPage }
];
但是,如果您确实需要路由/notfound
,请将的重定向到:'/notfound'
重定向到:'notfound'
,因为Angular尝试按照您在路由数组中声明的顺序匹配路由。您可以执行以下操作:
const appRoutes3: Routes = [
{
path: '',
children: [
{
path: 'login',
component: LoginPage
}
},
{ path: '**', component: NotFoundPage }
];
但是,如果确实需要路由/notfound
,请将重定向到“/notfound”
的重定向到:“notfound”您需要使用通配符(**)。**路径应为最后一条路由。如果请求的URL与配置中定义的路由的任何路径不匹配,路由器将选择此路由。这对于显示“404-未找到”页面或重定向到其他路由非常有用
const appRoutes: Routes = [
{ path: 'crisis-center', component: CrisisListComponent },
{ path: 'hero/:id', component: HeroDetailComponent },
{
path: 'heroes',
component: HeroListComponent,
data: { title: 'Heroes List' }
},
{ path: '',
redirectTo: '/heroes',
pathMatch: 'full'
},
{ path: '**', component: PageNotFoundComponent }
];
希望这有帮助。您需要使用一个通配符(**)。**路径应该是最后一条路由。如果请求的URL与配置中定义的路由的任何路径不匹配,路由器将选择此路由。这对于显示“404-未找到”页面或重定向到其他路由非常有用
const appRoutes: Routes = [
{ path: 'crisis-center', component: CrisisListComponent },
{ path: 'hero/:id', component: HeroDetailComponent },
{
path: 'heroes',
component: HeroListComponent,
data: { title: 'Heroes List' }
},
{ path: '',
redirectTo: '/heroes',
pathMatch: 'full'
},
{ path: '**', component: PageNotFoundComponent }
];
希望这有帮助。下面的代码在我的情况下运行良好
{ path: '404', component: PageNotFoundComponent }
在app.component.ts中添加以下代码
constructor(private router: Router) {
this.router.errorHandler = (error: any) => {
let routerError = error.toString();
if (routerError.indexOf('Cannot match any routes') >= 0 ) {
this.router.navigate(['/404']);
} else {
throw error;
}
}
}
以下代码在我的情况下运行良好
{ path: '404', component: PageNotFoundComponent }
在app.component.ts中添加以下代码
constructor(private router: Router) {
this.router.errorHandler = (error: any) => {
let routerError = error.toString();
if (routerError.indexOf('Cannot match any routes') >= 0 ) {
this.router.navigate(['/404']);
} else {
throw error;
}
}
}