1

Is there a way to do url in Angular?

http://www.example.com/?id=[1,2,3]&other=[4,5,6];

I created an object has object values.

let obj = {
    id:[1,2,3],
    other:[],
    someValues:null
}

this.router.navigate([], {queryParams: {id: obj.id}, relativeTo: this.route});

After redirect url converted to enter image description here

How can I solve?

3

2 Answers 2

3

I think that your format: http://www.example.com/?id=[1,2,3]&other=[4,5,6] is not the best way to pass arrays as query params.

The RFC6570 - URI Template defines how to do it, and in your case, correct way could be: http://www.example.com/?id=1,2,3&other=4,5,6

So consider refactor your code to adopt this more commonly used pattern.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot I will change my structure as you said.
I'am glad to help you :)
1

If you pass an array to the queryParams, angular will serialize it for you. This works for simple string arrays, but not for a complex array of objects.

For instance:

A queryParams like {id:[1,2,3]} will be parsed into ?id=1&id=2&id=3

A queryParams like {id:{key:"value"}} will be parsed into ?id=[object Object] (which is unusable)

If you want to pass an array or any JSON like data, I recommend using jsonurl to serialize the queryParams to the url and parse them later. This is way cleaner/safer than using JSON.serialize / JSON.parse

And if, like I, you would like angular to allow storing objects into urls with a minimum of effort, please consider voting up this issue

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.