最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 ?

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 ?

Share Improve this question edited Apr 26, 2016 at 6:41 QoP 28.4k16 gold badges77 silver badges76 bronze badges asked Apr 26, 2016 at 4:38 Rose18Rose18 3,1638 gold badges51 silver badges100 bronze badges 1
  • What do you mean, exactly? URLSearchParams only take string parameters because URL parameters are always strings. Any other type you'd have to convert to string, like you are doing. There's really not much else to say... – acdcjunior Commented Apr 26, 2016 at 4:48
Add a ment  | 

1 Answer 1

Reset to default 4

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);
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论