Ann18 Ann18 - 2 years ago 743
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 ?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download