Angular 18.2.10:Resolver中inject()失效及路由配置异常排查
Angular 18路由懒加载+包装组件+Resolver导入别名触发NG04014错误
问题描述
使用Angular 18.2.10,通过loadComponent实现路由懒加载,并用包装组件包裹所有子路由。仅使用loadComponent而不配置component时,触发错误:
ERROR RuntimeError: NG04014: Invalid configuration of route 'some-route/': routes must have either a path or a matcher specified
关键现象
- ✅ 为路径
''同时配置loadComponent和component,错误消失,但该方式不符合懒加载设计逻辑 - ✅ Resolver中
inject(HttpClient)可正常工作,但inject(SomeService)会触发上述NG04014错误 - ✅ 将
SomeService的导入从TypeScript路径别名@my/services改为相对路径../../core/services/some.service后,问题消失,但这并非合理解决方案
最小可复现代码
// APP_ROUTES export const APP_ROUTES: Routes = [ { path: '', loadChildren: () => import('./some.routes').then(m => m.SOME_ROUTES) } ]; // SOME_ROUTES export const SOME_ROUTES: Routes = [ { path: '', loadComponent: () => import('./wrapper.component').then(m => m.WrapperComponent), // component: WrapperComponent, // ✅ 取消注释后错误消失 children: [ { path: '', loadComponent: () => import('./list.component').then(m => m.ListComponent), resolve: { data: dataResolver, // 🔥 触发NG04014 }, }, { path: ':id', loadComponent: () => import('./details.component').then(m => m.DetailsComponent), }, ], }, ]; // dataResolver export const dataResolver: ResolveFn<any> = () => { const service = inject(SomeService); // ❌ 与loadComponent配合时触发NG04014 return service.getData(); };
环境信息
- Angular: 18.2.10
- RxJS: 7.8.1
- TypeScript: 5.5.4
- Zone.js: 0.14.10
补充信息
// SomeService代码 @Injectable({ providedIn: 'root' }) export class SomeService { getData() { return 'Some data'; } }
// tsconfig路径配置 "baseUrl": "./", "paths": { "@my/services": ["src/app/core/services/public.ts"], }
疑问
请问这是Angular 18的Bug,还是我的路由配置有误?
内容的提问来源于stack exchange,提问作者Yuri Avetisyan
相关产品推荐
相关产品推荐

