Angular编程式跳转指定路由异常问题求助
解决Angular路由跳转被重定向到Dashboard的问题
看起来你的问题核心出在路由路径的解析方式上,我来帮你拆解一下原因和解决方案:
问题根源
你的按钮所在组件大概率是在DashboardModule下(当前路由为/dashboard),当你使用:
this.router.navigate(['client/clie/', 1900001], {relativeTo: this.route});
时,relativeTo: this.route会让路径相对于当前的/dashboard路由进行解析,最终得到的路径是/dashboard/client/clie/1900001——这个路径在你的路由配置里不存在,所以触发了根路由的重定向规则(path: '' redirectTo: 'dashboard')。
而你第一次尝试的this.router.navigate(['client/clie/', 1900001]),如果没有指定相对上下文,Angular会根据当前路由的层级去解析,同样可能生成错误的路径。
解决方案
1. 使用绝对路径导航(最直接的解决方式)
在路径前加上斜杠/,让Angular从根路由开始解析路径:
// 推荐写法:把参数单独拆分出来 this.router.navigate(['/client/clie', 1900001]); // 或者拼接成完整路径字符串 this.router.navigate(['/client/clie/' + 1900001]);
这样就能直接匹配到CustomerRoutes中定义的/client/clie/:customerReference路径,不会触发重定向。
2. 验证路由配置的完整性
先确认你的路由配置语法正确(你给出的代码里有语法缺失,修正后的完整配置如下):
// app.routing.ts export const AppRoutes: Routes = [ { path: '', redirectTo: 'dashboard', pathMatch: 'full' }, { path: '', component: AdminLayoutComponent, children: [ { path: '', loadChildren: './moduleDashboard/dashboard.module#DashboardModule' }, { path: 'client', loadChildren: './moduleCustomer/customer.module#CustomerModule' } ] } ]; // CustomerRoutes export const CustomerRoutes: Routes = [ { path: '', children: [ { path: 'clil', component: CustomerListComponent }, { path: 'clie', component: CustomerAddComponent }, { path: 'clie/:customerReference', component: CustomerAddComponent } ] } ];
你的CustomerRoutes配置是正确的:父路由path: ''对应/client,子路由clie/:customerReference会被解析为/client/clie/:customerReference。
3. 可选:优化CustomerRoutes的默认路由
为了让路由更友好,可以给CustomerRoutes添加一个默认重定向,当用户访问/client时自动跳转到客户列表:
export const CustomerRoutes: Routes = [ { path: '', children: [ { path: 'clil', component: CustomerListComponent }, { path: 'clie', component: CustomerAddComponent }, { path: 'clie/:customerReference', component: CustomerAddComponent }, { path: '', redirectTo: 'clil', pathMatch: 'full' } // 新增默认路由 ] } ];
内容的提问来源于stack exchange,提问作者TheBoubou
相关产品推荐
相关产品推荐

