Angular路由匹配失败求助:auth/login与auth/register路由异常
Angular路由匹配错误:Cannot match any routes. URL Segment: 'auth/login' / 'auth/register'
问题根源
你的路由配置存在路径重复嵌套的问题:
AppRoutingModule中已经将/auth路径指向了AuthenticationModule- 但
AuthenticationRoutingModule又在外层路由中设置了path: 'auth',这会导致实际路由被解析为auth/auth/login,自然无法匹配期望的auth/login路径
解决方案
1. 修改AuthenticationRoutingModule的路由配置
去掉外层的path: 'auth',因为该前缀已经在AppRoutingModule中定义,直接基于空路径配置父组件和子路由:
const routes: Routes = [ { path: '', // 对应AppRouting中的/auth路径 component: AuthenticationComponent, children: [ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', loadChildren: () => LoginModule }, { path: 'register', loadChildren: () => RegisterModule } ] } ];
2. 保留Login/Register模块的路由配置
LoginRoutingModule和RegisterRoutingModule的配置无需修改,它们的空路径会自动对应父路由的login/register后缀:
LoginRoutingModule:
const routes: Routes = [ { path: '', component: LoginComponent } ];
RegisterRoutingModule:
const routes: Routes = [ { path: '', component: RegisterComponent } ];
3. 保持AppRoutingModule配置不变
原配置已经正确将/auth路径指向AuthenticationModule,无需调整:
const routes: Routes = [ { path: 'characters', loadChildren: () => AllCharactersModule, canActivate: [AuthGuard] }, { path: '', redirectTo: 'characters', pathMatch: 'full'}, { path: 'characters/:id', loadChildren: () => DifferentCharacterModule }, { path: 'auth', loadChildren: () => AuthenticationModule } ];
生效逻辑
当访问auth/login时:
AppRoutingModule匹配到auth路径,加载AuthenticationModuleAuthenticationRoutingModule处理剩余的login路径,匹配子路由中的login项并加载LoginModuleLoginModule的空路由对应login后缀,最终在AuthenticationComponent的<router-outlet>中渲染LoginComponent
内容的提问来源于stack exchange,提问作者Alexandr Boroshenko
相关产品推荐
相关产品推荐

