Ann18 Ann18 - 5 months ago 82x
Javascript Question

Angular 2: How to set double, float, int & boolean type params in GET & POST requests

In Angular 2 we are using URLSearchParams to set URL parameters in GET & POST requests.

var params = new URLSearchParams();
params.set('param1', param1);

I am using following way to use double and int type params.

longitude: number;
size: number;
params.set('longitude', longitude.toString());
params.set('size', size.toString());

But we can use only String type parameters here. What would be the best way to use double, float and boolean type parameters ?


As the names implies, URLSearchParams are part of the URL. URLs are need to be represented as string. If you need to distinguish between string, double float and boolean, then you can invent your own encoding and parse it accordingly on the receiver site.

An example:

var floatStr = encodeURIComponent(JSON.stringify({type: 'float', value: longitude.toString()}));
// params.set('param1', floatStr);


var json = JSON.parse(decodeURIComponent(param1));
if(json.type === 'float') {
  var longitude = parseFloat(json.value);