首页 > 解决方案 > 嵌套模块的 Angular 404 页面路由

问题描述

我在我的项目中使用嵌套模块

.
└─ AppModule
    ├─ MallModule
    ├─ OtherModule
    └─ ...

在主路由中,我只配置了顶级路由:

应用程序路由.module.ts

const routes: Routes = [
  { path: '',   redirectTo: '/', pathMatch: 'full' },
  { path: 'login', component: LoginComponent},
  { path: 'register', component: RegisterComponent },

  { path: '404', component: NotfoundComponent },
  { path: '**', redirectTo: '404' }, // Added
]

另外,我在每个子模块中分别配置了路由,例如:

商场路由.module.ts

const routes: Routes = [
  {
    path: '', 
    component: MallComponent,
    children: [
      {
        path: '',
        component: HomeComponent,
      },
      {
        path: 'about',
        component: AboutComponent,
      },
      ...
    }
]

结果是,因为在主路由配置中没有定义其他路由,所以除了 login/register/404 之外的所有请求都将被重定向到 404。

无论如何我可以使用正确的 404 重定向但保留当前的路由文件结构吗?我不希望将所有路由配置收集在一起。

谢谢!

标签: javascriptangulartypescript

解决方案


在您的应用程序模块中导入“其他”模块,这将允许使用这些模块中定义的路由。

更新后的代码应如下所示:

imports: [
  MallModule,
  OtherModule
  RouterModule.forRoot([ // Add the configuration here, which is not a part of other module ])
]

推荐阅读