Angular Router:如何将路径参数中的斜杠视为参数一部分
这个场景我之前开发时也碰到过,Angular默认会把URL里的斜杠解析成路由段的分隔符,直接把带斜杠的参数拼进导航路径里,会被拆成多个路由片段,导致匹配失败。下面给你两种可行的解决方案:
方案一:参数编码+解码(推荐,符合路由规范)
这种方法通过编码把参数里的特殊字符转成URL安全格式,避免Angular误解析:
修改导航代码:
在导航前用encodeURIComponent()对参数进行编码:const encodedCode = encodeURIComponent(this.groupListPage[0].code); this.router.navigate(['dashboard', encodedCode]);导航后URL会变成
http://localhost:4200/dashboard/T64%2F27D,Angular会把T64%2F27D识别为单个路由参数。路由配置保持常规:
路由配置不需要改动,依然是:const routes: Routes = [ // 其他路由... { path: 'dashboard/:code', component: YourDashboardComponent } ];组件内解码参数:
在目标组件中,通过ActivatedRoute获取参数后用decodeURIComponent()还原:import { ActivatedRoute } from '@angular/router'; constructor(private route: ActivatedRoute) {} ngOnInit(): void { this.route.paramMap.subscribe(params => { const code = decodeURIComponent(params.get('code')!); // 这里code就还原成了'T64/27D',可以正常使用 }); }
方案二:通配符路由捕获所有片段
如果不想用编码,也可以通过通配符路由捕获dashboard后面的所有内容,再手动拼接成参数:
修改路由配置:
使用**通配符匹配dashboard之后的所有URL片段:const routes: Routes = [ // 其他路由... { path: 'dashboard/**', component: YourDashboardComponent } ];组件内拼接参数:
在目标组件中,通过ActivatedRoute的url属性获取所有路由片段,再拼接成完整参数:import { ActivatedRoute } from '@angular/router'; constructor(private route: ActivatedRoute) {} ngOnInit(): void { this.route.url.subscribe(segments => { // segments[0]是'dashboard',从索引1开始的片段都是参数部分 const code = segments.slice(1).map(segment => segment.path).join('/'); // 这里code就是'T64/27D' }); }
为什么原来的代码会报错?
你之前的导航代码this.router.navigate(['dashboard/'+this.groupListPage[0].code]),Angular会把拼接后的字符串'dashboard/T64/27D'自动拆分成路由数组['dashboard', 'T64', '27D'],它会尝试匹配包含三个段的路由,但你的路由配置只有dashboard/:code(两个段),所以就会出现Cannot match any routes的错误。
内容的提问来源于stack exchange,提问作者infodev

