Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build query string from parameters object

How to build a url with query parameters in Angularjs.

I see the API $location.search()

the problem is $location(url) is to redirect to the url. In my case, I want to pass a url and key:value pairs for the query params and build the url. something like

url: /a/b/c params: {field1: value1, field2: value2}

result: /a/b/c?field1=value1&field2=value2

I like to use this url for links. I have also seen angular encode ? , & characters. Can I avoid this?

Edit:

My intention was to use the url as href for anchor elements. I do use $http to send the request, but sometimes I need to provide a link, with query params (based on the current object)

Thanks

like image 257
bsr Avatar asked Sep 06 '13 20:09

bsr


People also ask

Can query parameters be objects?

2. Query Parameters in OpenAPI 2. OpenAPI 2 doesn't support objects as query parameters; only primitive values and arrays of primitives are supported. Because of that, we'll instead want to define our JSON parameter as a string.

How do you create a query string?

An easy way to build a query string in Javascript is to use a URLSearchParams object: var query = new URLSearchParams(); query. append("KEY", "VALUE");

Can we send object in query string C#?

But anyway, if you want to send as query string you can do following: Convert object into string. Encode string. Append as parameter.


1 Answers

There is a nice solution as of 1.4+. You can build a query string from a parameters object with $httpParamSerializer :

var qs = $httpParamSerializer(params); 

See docs here

Default $http params serializer that converts objects to strings according to the following rules:

{'foo': 'bar'} results in foo=bar {'foo': Date.now()} results in foo=2015-04-01T09%3A50%3A49.262Z (toISOString() and encoded representation of a Date object) {'foo': ['bar', 'baz']} results in foo=bar&foo=baz (repeated key for each array element) {'foo': {'bar':'baz'}} results in foo=%7B%22bar%22%3A%22baz%22%7D" (stringified and encoded representation of an object) Note that serializer will sort the request parameters alphabetically. 
like image 152
Armel Larcier Avatar answered Sep 21 '22 22:09

Armel Larcier