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

Angular模块路由懒加载异常:访问/products路由报NG04002错误

解决Angular懒加载ProductModule时NG04002路由匹配错误的问题

NG04002错误本质是路由匹配失败,找不到对应路径的路由配置。直接导入ProductModule能正常工作,说明组件本身没问题,问题出在懒加载的路由配置环节,常见原因及修复方式如下:

常见原因及修复

1. AppRoutingModule懒加载路由配置错误

懒加载路由必须使用loadChildren指定模块路径,不能直接用component字段(那是即时加载的写法)。

  • 错误示例:
    // 错误:直接指定component,不是懒加载
    { path: 'products', component: ProductComponent }
    
  • 正确配置:
    const routes: Routes = [
      // 其他根路由
      {
        path: 'products',
        loadChildren: () => import('./product/product.module').then(m => m.ProductModule)
      }
    ];
    

2. ProductModule未配置正确的子路由

懒加载模块需要有独立的路由模块(比如ProductRoutingModule),且路由路径要和根路由的懒加载路径匹配:

  • 错误情况:如果ProductRoutingModule里把路径设为products,会形成/products/products的嵌套路径,而你访问的是/products,自然匹配失败。
  • 正确的ProductRoutingModule配置:
    const routes: Routes = [
      { path: '', component: ProductComponent } // 空路径对应根路由的/products
    ];
    
  • 同时确保ProductModule正确导入ProductRoutingModule:
    @NgModule({
      declarations: [ProductComponent],
      imports: [CommonModule, ProductRoutingModule]
    })
    export class ProductModule { }
    

3. AppModule同时导入了ProductModule

如果AppModule的imports数组里同时存在ProductModule和AppRoutingModule,会导致ProductModule被即时加载,和懒加载配置冲突,必须移除ProductModule:

@NgModule({
  imports: [BrowserModule, AppRoutingModule], // 仅保留AppRoutingModule,不要ProductModule
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

验证步骤

  1. 重启Angular开发服务器,确保配置变更生效
  2. 导航到http://localhost:4200/products,检查路由是否正常匹配

内容的提问来源于stack exchange,提问作者Ashish Kumar Jaryal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:23:13