Angular 10使用模块化路由时如何正确配置全局404处理
Angular 模块化路由全局404配置方案
问题根因
Angular 路由遵循从上到下、优先匹配先定义规则的逻辑,全局404通配符路由**如果注册顺序早于子模块路由,所有未匹配根路由规则的请求会直接被404拦截,子模块路由没有机会参与匹配。
实现方案
步骤1:调整根模块导入顺序
所有带路由定义的业务子模块,必须在AppModule中先于AppRoutingModule导入,确保子模块路由提前完成注册:
// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { PagesModule } from './pages/pages.module'; // 优先导入带路由的业务子模块 import { AppRoutingModule } from './app-routing.module'; // 后导入根路由模块 import { AppComponent } from './app.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; @NgModule({ declarations: [ AppComponent, PageNotFoundComponent ], imports: [ BrowserModule, PagesModule, // 业务子模块导入顺序必须早于AppRoutingModule AppRoutingModule ], bootstrap: [AppComponent] }) export class AppModule { }
步骤2:调整根路由配置
将404通配符路由放在根路由数组的最后一位,确保所有明确的路由规则(包括子模块注册的路由)都优先匹配:
// app-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, // 所有业务路由规则/子模块路由均已提前注册,无需在此重复定义 { path: '**', component: PageNotFoundComponent }, // 通配符路由必须放在路由数组最后一位 ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
懒加载子模块适配(可选)
如果子模块采用懒加载方式引入,无需提前导入子模块,直接将懒加载路由定义在通配符路由之前即可:
// 懒加载场景的根路由配置 const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, // 懒加载子模块路由定义在通配符之前 { path: 'home', loadChildren: () => import('./pages/home-page/home-page.module').then(m => m.HomePageModule) }, { path: 'test', loadChildren: () => import('./pages/test-page/test-page.module').then(m => m.TestPageModule) }, // 最后放置通配符路由 { path: '**', component: PageNotFoundComponent }, ];
内容的提问来源于stack exchange,提问作者user2977468
相关产品推荐
相关产品推荐

