Angular中带查询参数的URL被重定向至根路径问题咨询
Angular懒加载路由跳转问题修复方案
核心缺失配置
你没有在子模块中注册定义好的子路由规则,Angular无法识别子模块下的路径匹配逻辑,加载完子模块后找不到对应路由,最终命中父模块的**通配符规则,触发重定向到根路径。
你需要在MyAppModule的@NgModule装饰器的imports数组中添加RouterModule.forChild(routes)注册子路由,示例如下:
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { MyAppComponent } from './my-app.component'; // 替换为你存放子路由数组的实际文件路径 import { routes } from './my-app.routes'; @NgModule({ declarations: [MyAppComponent], imports: [ // 其他子模块依赖导入 RouterModule.forChild(routes) // 必须添加此行完成子路由注册 ] }) export class MyAppModule {}
其他可排查项
- 确认
AuthGuard的canActivate方法返回值为true,如果守卫校验不通过返回false或UrlTree,也会触发路由跳转中断,走到重定向逻辑 - 如果你使用Angular 8及以上版本,建议将字符串形式的
loadChildren改为动态导入语法,避免手写字符串路径出错导致模块加载失败:// app.module.ts 路由配置修改示例 const appRoutes: Routes = [ { path: "your-app", canActivate: [AuthGuard], loadChildren: () => import('./components/your-app/your-app.module').then(m => m.YourAppModule) }, { path: "my-app", canActivate: [AuthGuard], loadChildren: () => import('./components/my-app/my-app.module').then(m => m.MyAppModule) }, { path: "**", redirectTo: "/" } ];
内容的提问来源于stack exchange,提问作者Code Guru
相关产品推荐
相关产品推荐

