simonmikkelsen
simonmikkelsen

Reputation: 92

Angular navigate also encodes ? and = of the queryParams

In Angular I navigate to a page and wants to give it a returnUrl as parameter. I do it in this way:

this.router.navigate(['/validation'], { queryParams: { returnUrl: state.url }});

But this causes the url to be:

https://myhost/myapp/validation%3FreturnUrl%3D%252FmyUrl

where I expected it to be

https://myhost/myapp/validation?returnUrl=%2FmyUrl

When I read the documentation, the URL should be encoded exactly as I expect: The values should be encoded, but ? be intact.

The wrongly encoded URL results in my app cannot find the /validation URL and sends the navigation to Angulars 404 handling.

Any idea what could be wrong?

Upvotes: 1

Views: 1410

Answers (1)

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

Yes, Angular might be encoding the URL component, but you can use decodeURIComponent when you want to use it:

const url = "https://myhost/myapp/validation%3FreturnUrl%3D%252FmyUrl";
const decodeURL = decodeURIComponent(url);
console.log(decodeURL)

Below code will get you the methods/properties to work on the URL i.e URL.searchParams.get('returnUrl')

 const URL = new URL(decodeURL);
 console.log(URL);

It will work as expected and get the parameter from it.

Upvotes: 1

Related Questions