我只是无法弄清楚这个问题的解决方案。我正在设计搜索引擎,我想在url中显示用户试图找到的内容如下:
https://my-site.com/search;query=%28rockstar;search=true;page=0
用户正试图找到(rockstar
短语。
当我将此网址粘贴到浏览器时,它按预期工作,但Chrome浏览器正在显示此网址,如下所示:
https://my-site.com/search;query=(rockstar;search=true;page=0
所以%28
改为(
。我不知道这种行为是否依赖于Angular或Browser。当我有(
的网址时,刷新F5
无法正常工作,因为Angular Router报告的问题如下:
Cannot match any routes. URL Segment: 'rockstar;search=true;page=0'
从URL地址栏复制链接也没用,因为这种行为复制的链接包含(
字符(不是%28
)。如何防止%28
和其他特殊字符不被浏览器在url地址栏中解码?问题出现在Angular v5.2.5中
这是这个问题的演示:https://angular-url-problem.stackblitz.io
请注意,在Angular 6中,问题不存在:https://angular-url-problem-v6.stackblitz.io
它不起作用,因为你没有看到正确的参数。在this stackblitz中,正如您所看到的,您甚至不需要对参数进行编码。
您也不需要过多地创建查询参数。 Angular提供高级抽象,使用它对您有利。
ngOnInit(): void {
this._route.queryParamMap
.subscribe(params => {
this.form.patchValue({
query: params.get('query') || '',
});
});
}
public onSubmit(): void {
const query: string = this.form.value.query;
this._router.navigate(['/search'], {
queryParams: {
query
}
})
}
使用矩阵表示法编辑:stackblitz
ngOnInit(): void {
this._route.params
.subscribe(params => {
this.form.patchValue({
query: params['query'] || '',
});
});
}
public onSubmit(): void {
const query: string = this.form.value.query;
this._router.navigate(['/search', { query }]);
}