angular 路由参数值中带有“&”的路由链接
angular routerlink with '&' in route parameter value
您好,我遇到了一个问题,因为我有一个包含“&”字符的路由参数。这是我的路线配置:
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full'},
{path: 'home', component: HomeComponent},
{path: 'work', component: WorkComponent},
{path: 'who', component: WhoComponent},
{path: 'process', component: ProcessComponent},
{path: 'services', component: ServicesComponent},
{path: 'project/:name', component: ProjectComponent}
];
这是我的 link:
<button class="some-class" [routerLink]="'/project/R&D more text here'">R&D Things and stuff</button>
第一次单击 link 时一切正常,激活了正确的路由并且名称路由参数获得了完整的字符串值。问题出在页面刷新上,路由器正在将 url 更改为:
http://localhost:4200/project/R
处理此路由问题的最佳方法是什么?
您可以使用 encodeURIComponent("R&D some other text here")
对其进行正确编码。
因此在您的组件中创建一个 属性:
url = `/project/${encodeURIComponent('R&D Some Other Text')}`;
然后在您的模板中:
<button class="some-class" [routerLink]="url">R&D Things and stuff</button>
当你想捕获路由参数的name
属性时,可以使用ActivatedRoute,然后使用decodeURIComponent
解码name
:
constructor(private route: ActivatedRoute) {}
...
ngOnInit() {
this.route.params
.subscribe(params => {
const name = decodeURIComponent(params['name']);
console.log(name);
...
});
...
}
这里有一个 Working StackBlitz 供您参考。
您好,我遇到了一个问题,因为我有一个包含“&”字符的路由参数。这是我的路线配置:
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full'},
{path: 'home', component: HomeComponent},
{path: 'work', component: WorkComponent},
{path: 'who', component: WhoComponent},
{path: 'process', component: ProcessComponent},
{path: 'services', component: ServicesComponent},
{path: 'project/:name', component: ProjectComponent}
];
这是我的 link:
<button class="some-class" [routerLink]="'/project/R&D more text here'">R&D Things and stuff</button>
第一次单击 link 时一切正常,激活了正确的路由并且名称路由参数获得了完整的字符串值。问题出在页面刷新上,路由器正在将 url 更改为:
http://localhost:4200/project/R
处理此路由问题的最佳方法是什么?
您可以使用 encodeURIComponent("R&D some other text here")
对其进行正确编码。
因此在您的组件中创建一个 属性:
url = `/project/${encodeURIComponent('R&D Some Other Text')}`;
然后在您的模板中:
<button class="some-class" [routerLink]="url">R&D Things and stuff</button>
当你想捕获路由参数的name
属性时,可以使用ActivatedRoute,然后使用decodeURIComponent
解码name
:
constructor(private route: ActivatedRoute) {}
...
ngOnInit() {
this.route.params
.subscribe(params => {
const name = decodeURIComponent(params['name']);
console.log(name);
...
});
...
}
这里有一个 Working StackBlitz 供您参考。