Angular 5中router.navigate路由跳转异常,无法跳转至指定路径
解决Angular路由导航被重定向到Dashboard的问题
看起来你遇到的问题主要是导航路径的写法错误,加上相对路径的使用不当,导致路由无法匹配,最终触发了根路由的重定向规则。下面一步步分析问题并给出解决方案:
问题分析
先看你尝试的几种导航写法里的问题:
- 第一种写法有语法错误:
this.router.navigate([/client/clid/1900001}]);里的路径字符串多了一个多余的},生成的路径是/client/clid/1900001},这显然是无效路径,Angular找不到匹配的路由就会触发根路由的重定向到dashboard。 - 第二种写法冲突:同时使用绝对路径(以
/开头)和relativeTo,relativeTo会被绝对路径忽略,不过这个路径本身是正确的,如果还是重定向,可能是其他配置问题,但先看其他写法。 - 第三种写法错误使用路由占位符:
['client/clid/:customerReference', myCustomerReference]里的:customerReference是路由定义时的占位符,导航时不需要写,应该直接传参数值。 - 第四种写法相对路径错误:当前你在
CustomerListComponent,对应的路径是/client/clil,使用['client/clid', 1900001]会生成相对路径/client/clil/client/clid/1900001,这是无效路径,自然会被重定向。
解决方案
方案1:使用正确的绝对路径导航
修正语法错误,直接使用绝对路径跳转:
myFunction() { const myCustomerReference = 1900001; // 注意去掉多余的},确保路径格式正确 this.router.navigate([`/client/clid/${myCustomerReference}`]); }
方案2:使用正确的相对路径导航
如果你想基于当前路由使用相对路径,需要回到父路径(/client)再跳转,用../表示父级路径:
myFunction() { const myCustomerReference = 1900001; // ../ 回到/client路径,再进入clid/:customerReference this.router.navigate(['../clid', myCustomerReference], { relativeTo: this.route }); }
额外验证步骤
- 检查CustomerModule的路由配置:确保你的
CustomerModule正确导入了路由配置,比如:
// customer.module.ts import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CustomerRoutes } from './customer.routing'; import { CustomerListComponent, CustomerAllDetailComponent } from './your-component-path'; @NgModule({ imports: [RouterModule.forChild(CustomerRoutes)], declarations: [CustomerListComponent, CustomerAllDetailComponent] }) export class CustomerModule { }
- 用routerLink测试路径有效性:在
CustomerListComponent的模板里添加测试链接,验证路径本身是否能正常跳转:
<a routerLink="/client/clid/1900001">测试跳转客户详情</a>
如果点击这个链接能正常跳转到目标页面,说明路由配置没问题,只是导航代码的写法错误;如果还是重定向,那需要检查app.routing.ts里的路由顺序,确保path: 'client'的路由在path: ''的Dashboard路由之后(Angular路由是按顺序匹配的,你的现有配置顺序是正确的)。
- 简化CustomerRoutes配置(可选):你当前的
CustomerRoutes外层套了一层path: ''的父路由,其实可以简化成直接定义子路由,这样更清晰:
export const CustomerRoutes: Routes = [ { path: 'clil', component: CustomerListComponent }, { path: 'clid/:customerReference', component: CustomerAllDetailComponent } ];
因为CustomerModule已经加载在/client路径下,所以这些路由会自动相对于/client,效果和原来的配置一致,但可读性更好。
内容的提问来源于stack exchange,提问作者TheBoubou
相关产品推荐
相关产品推荐

