You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular多子模块路由问题:子路由匹配失败(NG04002错误)

Angular子路由NG04002: Cannot match any routes 解决方案

问题根源

  1. 父路由未配置子模块路由入口:AppRoutingModule中没有对应/planning路径的路由规则,Angular无法将该路径关联到PlanningModule。
  2. 子路由路径定义错误:PlanningRoutingModule中使用path: 'planning',结合forChild的相对路由特性,实际会生成/planning/planning的路由规则,但你的路由链接指向的是/planning,自然匹配失败。

修复步骤

步骤1:更新父路由配置

在AppRoutingModule的routes数组中添加指向PlanningModule的路由条目,推荐使用懒加载的模块化方式:

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { HomeListComponent } from './home-list/home-list.component';
import { ListesHomeComponent } from './listes/listes-home/listes-home.component';
import { NotFoundComponent } from './not-found/not-found.component';

const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'listes', component: ListesHomeComponent },
  // 懒加载Planning模块,访问/planning时动态加载
  { 
    path: 'planning', 
    loadChildren: () => import('./planning/planning.module').then(m => m.PlanningModule) 
  },
  { path: '', component: HomeListComponent },
  { path: '**', component: NotFoundComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

若使用懒加载,需从AppModule的imports数组中移除PlanningModule。

如果要保持当前非懒加载的结构,可改用children配置:

// app-routing.module.ts
const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'listes', component: ListesHomeComponent },
  { 
    path: 'planning', 
    children: [] 
  },
  { path: '', component: HomeListComponent },
  { path: '**', component: NotFoundComponent },
];

步骤2:修正子路由路径

将PlanningRoutingModule中的路由路径改为空字符串,匹配父路由/planning下的默认组件:

// planning-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PlanningHomeComponent } from './planning-home/planning-home.component';

// 空路径对应父路由的/planning路径
const routes: Routes = [{ path: '', component: PlanningHomeComponent }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class PlanningRoutingModule {}

验证路由链接

你的路由链接代码无需修改,routerLink="planning"会正确指向/planning路径:

<a
  routerLink="planning"
  routerLinkActive="active"
  class="nav-link"
  aria-current="page"
>Planning</a>

补充说明

  • RouterModule.forRoot()用于根路由配置,forChild()用于子模块路由配置,子路由路径相对于父路由。
  • 确保FrameworkComponent中包含<router-outlet></router-outlet>标签,这是Angular渲染路由组件的出口。

内容的提问来源于stack exchange,提问作者Jean-Sébastien Lasne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:45:51