将数组传递到URLSearchParams,同时使用http调用获取请求

时间:2016-08-05 20:43:39

标签: angular angular2-http

通过URLSearchParams的Angular文档,我找到了关于将数组作为参数传递的任何文档。

有人可以帮忙吗?

6 个答案:

答案 0 :(得分:29)

实际上,您不能直接传递数组,但可以多次使用import RPi.GPIO as GPIO channel = 11 # Setup your channel GPIO.setup(channel, GPIO.OUT) GPIO.output(channel, GPIO.LOW) # To test the value of a pin use the .input method channel_is_on = GPIO.input(channel) # Returns 0 if OFF or 1 if ON if channel_is_on: # Do something here 方法:

append

答案 1 :(得分:1)

URLSearchParams可以传递成对的序列,以便具有一个值数组:

var ids = [1,2,3,4]
var search = new URLSearchParams(ids.map(s=>['id',s]))
var searchString = search.toString()
// "id=1&id=2&id=3&id=4"
// To get the ids from the URL search string
var search_ids = [...search.getAll('id')]

答案 2 :(得分:1)

const buildParams = (search) => {
  if (!search) return "";

  const params = new URLSearchParams();

  Object.entries(search).forEach(([key, value]) => {
    if (Array.isArray(value)) params.append(key, value.join(","));
    else params.append(key, value.toString());
  });

  return `?${params}`;
};

const search = {
  types: ['good', 'bad', 'normal'],
  id: 777
}

const url = `http://good.com/${buildParams(search)}`;

结果,您将获得 http://good.com/?types=good,bad,normal&id=777

答案 3 :(得分:0)

我已使用Lodash map遍历对象/数组并动态附加参数。


const buildParams = (data) => {
  const params = new URLSearchParams();

  map(data, (value, key) => {
    if (Array.isArray(data[key])) {
      map(value, item => params.append(key, item));
    } else {
      params.append(key, value);
    }
  });

  return params;
};

const params = {
  foo: ['a', 'b', 'c'],
  bar: 'xyz'
}

const doFetch = fetch(`http://api.com/search?${buildParams(params)}`)

因此,最终的网址应类似于:http://api.com/search?foo=a&foo=b&foo=c&bar=xyz

答案 4 :(得分:0)

         makeSearchParams(link){
            var url = new URL(window.location.protocol + '//' + window.location.host + link);
            const params = this.getSearchParams();

            for(let key in params){
                if(Array.isArray(params[key])){
                    for(let key1 in params[key]){
                        url.searchParams.append(key +'[]', params[key][key1]);
                    }
                }
                else
                    url.searchParams.append(key, params[key]);
            }
            return url;
        }

答案 5 :(得分:0)

其实这是最简单的函数方式:

const url = new URL('http://localhost/')
url.searchParams.append('date[0]', date1)
url.searchParams.append('date[1]', date2)
console.log(url.toString())

当然你可以遍历一个数组。