带有可选参数的 Typescript 构建 URL

Typescript building URL with optional arguments

我正在尝试构建一个 URL 以从 REST 服务获取数据,有效的 url 应该如下所示

http://SITENAME/api/get_posts/?count=5&page=1&post_type=gallery

我有像 countpagepost_type 和更多的.. 这些是可选参数,一个或全部可以为空 我尝试了以下代码

var query = 'http://localhost/wptest/api/get_posts/?';
fetchData(countIn: int, pageIn: int, typeIn: string, query: string) {

    if (this.countIn)   //if count not null, add count parameter.
        query = `${query}&count=${this.countIn}`;
    if (this.pageIn)  
        query = `${query}&page=${this.pageIn}`;
    if (this.typeIn)  
        query = `${query}&post_type=${this.typeIn}`;

    return this.http.get(query).map(res => res.json());
}

当我转到 chrome 调试器 => 网络选项卡时,这个丑陋的代码返回了一个无效的 URL,我发现:

但是我没有得到异常,因为不知何故 url 得到修复并使用有效的 url:

发送新请求

问题在于 ?count=5&page=1?&count=5&page=1

之间的区别

这导致选项卡微调器卡住并且永远不会结束。

问:为了获得有效的 URL,可以对代码做哪些改进?

尝试:

var query = 'http://localhost/wptest/api/get_posts/?';
var counter = 0;
fetchData(countIn: int, pageIn: int, typeIn: string, query: string) {

if (this.countIn && counter = 0){  //if count not null, add count parameter.
    query = `${query}count=${this.countIn}`;
counter++;
}
elseif(this.countIn){  //if count not null, add count parameter.
    query = `${query}&count=${this.countIn}`;
} 

if (this.pageIn && counter = 0){  //if count not null, add count parameter.
    query = `${query}count=${this.pageIn}`;
counter++;
}
elseif(this.pageIn){  //if count not null, add count parameter.
    query = `${query}&count=${this.pageIn}`;
} 

if (this.typeIn && counter = 0){  //if count not null, add count parameter.
    query = `${query}count=${this.typeIn}`;
counter++;
}
elseif(this.typeIn){  //if count not null, add count parameter.
    query = `${query}&count=${this.typeIn}`;
} 



return this.http.get(query).map(res => res.json());
}

    query = `${query}&post_type=${this.typeIn}`;

我相信这是一个解决方法。

保持当前代码的一般结构,您可以添加一个变量,该变量在第一个实例被使用后用“&”设置。

fetchData(countIn: int, pageIn: int, typeIn: string, query: string) {
    var prepend = '';
    if (this.countIn)  { 
        query = `${query}` + prepend + `count=${this.countIn}`;
        prepend = '&';
    }
    if (this.pageIn)  {
        query = `${query}` + prepend + `page=${this.pageIn}`;
        prepend = '&';
    }
    if (this.typeIn)  {
        query =  `${query}` + prepend + `post_type=${this.typeIn}`;
        prepend = '&';
    }

    return this.http.get(query).map(res => res.json());
}

还有其他方法可以实现您想要完成的目标,但这是一种方法。

var params = [], // your params here
    self = this;
[["count", "countIn"], ["page", "pageIn"], ["post_type", "postIn"]]
  .forEach(function(param) { 
     if(self[param[1]]) params.push(param[0] + "=" + self[param[1]]); 
  });
var query = `${query}` + params.join("&");