【问题标题】:angular routerlink with '&' in route parameter value路由参数值中带有“&”的角度路由器链接
【发布时间】:2018-11-10 01:12:34
【问题描述】:

您好,我遇到了一个问题,因为我有一个包含“&”字符的路由参数。这是我的路线配置:

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

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

【问题讨论】:

    标签: angular angular-routing angular-router


    【解决方案1】:

    您可以使用encodeURIComponent("R&amp;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 供您参考。

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 2019-05-11
      • 2018-05-17
      相关资源
      最近更新 更多