angular 2 http请求为http请求创建查询字符串

时间:2016-10-05 09:27:23

标签: javascript angular

我有两个API需要两个不同的查询字符串/ param结构,我一直试图弄清楚如何做到这一点,但我没有到达任何地方。

两个API都是GET请求,但API 1 URL请求类似于

www.website.com/api/User?username=niceguy

API 2请求网址,因为它没有input它基本上只需点击一个按钮即可进行搜索,而API 1确实有一个input来构建它查询字符串结构。

www.website.com/api/User

两个不同的查询字符串但返回相同的对象,我只使用1个搜索功能进行动态处理,因此我发现很难构建查询字符串。

我创建了一个构建查询字符串的函数,但它只采用API 1结构。

有人可以指出HTTP请求如何也可以采用API 2结构吗?

function queryStringBuild() {
 let result: string = "?";
        //for each of the input search terms...
   this.searchBoxCount.forEach((inputSearch: any) => {
     // first reparse the input values to individual key value pairs
     // Checks which field is not null and with empty string (space)
     if (inputSearch.value != null && (inputSearch.value != "")) {
        let inputValues: string = inputSearch.value
             .split("\n")
             .filter(function (str) { return str !== "" })
             .join("&" + inputSearch.name + "=");
             // then add it to the overall query string for all searches
             result = result + inputSearch.name + "=" + inputValues + "&"
       }
   });
   // remove trailing '&'
   result = result.slice(0, result.length - 1);
   return result;
}

API请求

getRequest() {
 this.http.get('www.website.com/api/' + this.queryStringBuild)
 ...
}

1 个答案:

答案 0 :(得分:0)

我使用URLSearchParams提出了不同的解决方案。

let params = new URLSearchParams();
this.searchBoxCount.forEach((inputSearch: any) => {
    if (inputSearch.value != null && (inputSearch.value != "")) {
        let filteredValue = inputSearch.split("\n")
                                       .filter(x => x != "")
                                       .join(",");

        params.set(inputSearch.name, filteredValue);
    }
}

this.http.get('www.website.com/api', { search: params });

我不确切知道您的API是如何工作的,因此同一参数的多个值如何连接取决于您。

  

See this post for more information