Angular 路由器 URL 编码特殊字符和浏览器行为 [英] Angular Router URL Encoding Special Characters and Browser Behavior

查看:22
本文介绍了Angular 路由器 URL 编码特殊字符和浏览器行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想不出解决此类问题的方法.我正在设计搜索引擎,我想在 url 中显示用户试图找到的内容:

I just can't figure out the solution for such problem. I'm designing search engine and I'd like to display in url what user is trying to find like this:

https://my-site.com/search;query=%28rockstar;search=true;page=0

用户正在尝试查找 (rockstar 短语.

User is trying to find (rockstar phrase.

当我将此网址粘贴到浏览器时,它按预期工作,但 Chrome 浏览器显示此网址如下:

When I paste this url to the browser it works as expected but the Chrome browser is displaying this url like this:

https://my-site.com/search;query=(rockstar;search=true;page=0

所以 %28 更改为 (.我不知道这种行为是依赖于 Angular 还是浏览器.当我有带有 ( 然后刷新 F5 不起作用,因为 Angular Router 报告如下问题:

So the %28 is changed to (. I don't know if this behavior is Angular or Browser dependent. When I have url with ( then refreshing F5 is not working because Angular Router is reporting problem like this:

Cannot match any routes. URL Segment: 'rockstar;search=true;page=0'

从url地址栏复制链接也是无用的,因为复制的链接包含(字符(不是%28).如何防止%28等特殊字符在url地址栏中浏览器无法解码?问题出现在Angular v5.2.5

Copying link from url address bar is also useless because of this behavior the copied link contains ( character (not %28). How to prevent %28 and other special characters to be not decoded by Browser in url address bar? The problem arises in Angular v5.2.5

这是这个问题的演示:https://angular-url-problem.stackblitz.io

请注意,在 Angular 6 中不存在该问题:https://angular-url-problem-v6.stackblitz.io

Notice that in Angular 6 the problem doesn't exists: https://angular-url-problem-v6.stackblitz.io

推荐答案

它不起作用,因为您没有查看正确的参数.在这个stackblitz,如您所见,您甚至不需要对参数进行编码.

It doesn't work because you're not looking at the right params. In this stackblitz, as you can see, you don't even need to encode your parameters.

您也不需要走得太远来创建查询参数.Angular 提供了高级别的抽象,利用它可以为您带来好处.

You also don't need to go too far to create query params. Angular provides a high level of abstraction, use it to your advantage.

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

这篇关于Angular 路由器 URL 编码特殊字符和浏览器行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆