Angular自定义路由名称:如何将路由路径/userReport修改为/ReportSection
路由URL修改实现方案
首先说明你两次尝试未生效/报错的原因:
data属性属于路由自定义元数据,仅用于存储路由附加标识,不会修改实际匹配的URL路径,因此第一次配置无法生效。- 直接修改path为ReportSection后,原
/userReport路径无对应匹配规则,访问旧地址就会触发路由匹配报错。
下面提供两种常用实现方案,可根据你的需求选择:
方案1:新旧地址同时可用,均指向同一组件
直接在子路由中新增ReportSection路由,保留原有userReport路由即可:
Routes = [ { path: '', component: MainLayoutComponent, children: [ { path: 'activity', component: ActivityListComponent, pathMatch: 'full', canActivate: [AuthGuard] }, { path: 'userReport', component: ReportsComponent, pathMatch: 'full', canActivate: [AuthGuard] }, { path: 'ReportSection', component: ReportsComponent, pathMatch: 'full', canActivate: [AuthGuard] } ] } ]
配置完成后,http://localhost:1234/userReport和http://localhost:1234/ReportSection都可以正常访问到ReportsComponent。
方案2:仅保留新地址,旧地址自动跳转至新地址
添加重定向路由规则,将旧路径的请求全部重定向到新路径:
Routes = [ { path: '', component: MainLayoutComponent, children: [ { path: 'activity', component: ActivityListComponent, pathMatch: 'full', canActivate: [AuthGuard] }, // 旧路径重定向规则 { path: 'userReport', redirectTo: 'ReportSection', pathMatch: 'full' }, { path: 'ReportSection', component: ReportsComponent, pathMatch: 'full', canActivate: [AuthGuard] } ] } ]
该方案下访问旧地址/userReport会自动跳转至新地址/ReportSection,既满足URL修改需求,也不会出现路由匹配报错。如果你的项目内有硬编码跳转/userReport的逻辑,也可以同步修改为/ReportSection,不修改也可由重定向规则自动处理。
内容的提问来源于stack exchange,提问作者Virender Thakur
相关产品推荐
相关产品推荐

