2

I am trying to take a json object such as this one:

filters = {"filters": myArray};

and append it to the end of a url using:

this.router.navigate([`/devices/${productType}/${deviceCategory}/${JSON.stringify(filters)}`]);

Anyway, so I read on other forums that using encodeURIComponent should be used so then I tried the following:

this.router.navigate([`/devices/${productType}/${deviceCategory}/${encodeURIComponent(JSON.stringify(filters))}`]);

At this point I dont get errors but, when I try to get the data from params.paramId.filters I get undefined, even if I decode or parse it with JSON.parse(decodeURIComponent(params.paramId.filters));

How can I add a stringified object to a url and then retrieve it from the params to continue using it?

Thank you in advance!

1
  • 1
    You might want to consider encoding that as a query string instead of sticking JSON in path segments. Commented Aug 15, 2019 at 19:08

2 Answers 2

1

Encoding

First do this:

const source = new URLSearchParams(filters).toString();

and append this to your url:

encodeURIComponent(JSON.stringify(source));

Decoding

Do this:

var search = location.search.substring(1);
var filters = JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g,'","').replace(/=/g,'":"') + '"}');
Sign up to request clarification or add additional context in comments.

Comments

0

What I ended up doing was, I imported NavigationExtras, then:

let navigationExtras: NavigationExtras = {queryParams: {"filters": JSON.stringify(this.searchValues)}};

in my function where I was trying to append the parameter to the link, and added it like this:

this.router.navigate(['/devices/${this.config.productType.toLowerCase()}/${this.deviceCategory}/${this.displayMode}'], navigationExtras);

I retrieved it like this:

this.activatedRoute.queryParams.subscribe(param => { this.finalSearchValues = param["filters"] ? {"Filters": JSON.parse(param["filters"])} : {"filters":[]}; console.log(this.finalSearchValues);});

And it seems to be working for me at the moment. Thank you for your answers guys.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.