Angular Router URL Encoding Special Characters and Browser Behavior

谁说胖子不能爱 提交于 2020-01-06 05:22:15

问题


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

User is trying to find (rockstar phrase.

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

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'

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

Here is the demo with this problem: https://angular-url-problem.stackblitz.io

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


回答1:


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.

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

EDIT with matrix notation : 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 }]);
}


来源:https://stackoverflow.com/questions/52094849/angular-router-url-encoding-special-characters-and-browser-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!