路由参数值中带有“&”的角形路由器链接

时间:2018-11-09 16:48:59

标签: angular angular-routing angular-router

嗨,我遇到了一个问题,由于我有一个路由参数,其中包含一个'&'字符。这是我的路线配置:

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}
];

这是我的链接:

<button class="some-class" [routerLink]="'/project/R&D more text here'">R&D Things and stuff</button>

第一次单击链接,一切正常,激活正确的路由,名称路由参数获取完整的字符串值。问题在于刷新路由器将URL更改为以下页面:

http://localhost:4200/project/R

处理此路由问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用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