您可以在Angular中禁用辅助/辅助路线吗?

时间:2018-10-29 18:08:22

标签: angular url-routing

我的应用程序中有一个搜索字段,提交后,该字段会将用户导航到myapp.com/search/my search phrase here之类的URL。

我有一条路线可以很好地处理此问题:

{ path: 'search/:q', component: SearchResultsComponent } 

问题是,如果人们在搜索中使用括号,例如“ hello(世界)”,则路由器会崩溃,因为它正在寻找由括号内的部分指定的辅助路线/额外出口。

是否可以通过括号禁用此功能,并将完整的令牌传递给路由中的组件?

1 个答案:

答案 0 :(得分:0)

不,您不能禁用它,但是有一种解决方法:对百分比符号进行编码,然后在需要读取值的位置对其进行解码。

// Add this somewhere
export const fixedEncodeURIComponent = (str: string) => {
  return encodeURIComponent(str).replace(/[!'()*]/g, (c) => {
    return '%' + c.charCodeAt(0).toString(16);
  });
};


// In your component
this.router.navigate(['search', fixedEncodeURIComponent(query)]);