Angular路由异常:输入有效URL仍自动重定向至首页问题
Angular懒加载路由重定向问题解决
问题分析
访问localhost:4200/products时页面短暂显示后跳转到首页,核心原因是Services模块的路由配置与父路由不匹配:
- App路由中
products路径指向懒加载的ServicesModule,模块内的根路径''对应父路由的/products - 但ServicesModule的子路由设置了
path: 'products',这意味着只有访问/products/products才会匹配到TitleComponent - 当前
/products路径下,ServicesComponent加载后没有匹配的子路由,触发Angular路由的 fallback 逻辑,最终跳转到首页的空路径路由
解决方案
修改services-routing.module.ts的路由配置,让子路由匹配父路由的空路径:
const routes: Routes = [ { path: '', component: ServicesComponent, children: [{path: '', component: TitleComponent}] } ];
如果不需要ServicesComponent作为父容器,也可以直接简化为:
const routes: Routes = [ { path: '', component: TitleComponent } ];
验证
修改后访问localhost:4200/products,页面会稳定加载对应组件,不会再自动重定向到首页。
内容的提问来源于stack exchange,提问作者user22222422
相关产品推荐
相关产品推荐

