可以使用控制台打印来检查错误信息,然后将所有错误路由到404页面,包括子路由的错误。以下是一个示例代码:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NotFoundComponent } from './not-found/not-found.component';
const routes: Routes = [
{
path: '',
loadChildren: () => import('./home/home.module').then(m => m.HomeModule)
},
{
path: '**',
component: NotFoundComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在上面的代码中,NotFoundComponent
是你的404组件,如果路由无法匹配任何其他路由,则会自动路由到该组件。
然后可以在子路由中添加一个通配符路由来使普通路由错误也能被捕获并路由到404页面:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NotFoundComponent } from '../not-found/not-found.component';
import { ChildComponent } from './child.component';
const routes: Routes = [
{
path: '',
component: ChildComponent
},
{
path: '**',
component: NotFoundComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ChildRoutingModule { }
这样,当访问不存在的子路由时,它将路由到404页面。