1

I am fetching query parameter from url through ActivatedRoute queryParams method.It is working fine for normal string.But If I have '&' inside the query value,then it's split the value from '&' and getting the string before the '&' position.Example is below:

http://localhost:4200/#/test/APP?cat1=APP1&cat2=A&B%20Test=&cat3=Service this is the url from which I'm fetching the cat1,cat2,,cat3 value.

constructor(private actRoute: ActivatedRoute){
}
this.actRoute.queryParams.subscribe(params => {
     this.catName1 = params['cat1'];
     this.catName2 = params['cat2'];
     this.catName3 = params['cat3'];
     console.log(this.catName1, this.catName2);
})

this.catName1 is printing APP1 but this.catName2 is printing only A, rest of the part is omitted.How to get the whole this.catName2 value as A&B Test. I already tried with encodeURI() function but nothing happened.

Subham
  • 1,414
  • 4
  • 17
  • 34

1 Answers1

3

Angular is working as it should. & is used to separate query parameters in an URL. As such & has a special meaning in an URL. (Reference: https://en.wikipedia.org/wiki/Query_string) If your values have & in them, they should be URL encoded before being used.

To URL encode a string you can do in the browser console, encodeURI("<<URL>>"). The encoded version of your URL will be,

http://localhost:4200/#/test/APP?cat1=APP1&cat2=A&B%20Test=&cat3=Service

encodeURI however does not encode, , / ? : @ & = + $ #. Since one of your query params has & use encodeURIComponent instead. Note that encodeURIComponent should be used on the individual query params and not on the URL itself.

const params = {
  cat1: "APP1",
  cat2: "A&B Test",
  cat3: "Service"
};

for (const [key, value] of Object.entries(params)) {
  params[key] = encodeURIComponent(value);
}

console.log(params); // prints Object { cat1: "APP1", cat2: "A%26B%20Test", cat3: "Service" }

this.router.navigate(['/test/APP'], { queryParams: params });

sidthesloth
  • 1,399
  • 1
  • 11
  • 19
  • This url is same as of mine.Also I told that I alredy used `encodeURI()` and nothing happened. – Subham Sep 01 '20 at 04:43