使用TypeScript构建具有可选参数的URL

4
我正在尝试构建一个从REST服务获取数据的URL,有效的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());
}

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

enter image description here

然而,我没有收到异常提示,因为某种方式修复了URL并发送了一个带有有效URL的新请求:

enter image description here

问题出在?count=5&page=1?&count=5&page=1之间的差异,导致选项卡旋转器被卡住且无法结束。

enter image description here

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

3个回答

3
保留您当前代码的一般结构,您可以添加一个变量,在第一次使用“&”后被设置。
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());
}

你想要实现的目标还有其他方法,但这是一种实现方式。


很好的做法。 :) - Dray

2
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("&");

你有没有注意到${query}&中第一个参数前的字符&导致了整个问题? - Murhaf Sousli
抱歉我的错误。我匆忙写了这个程序,没有进行测试。 - Mikhail Vitik

0

尝试:

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

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


如果 count 为空,而我的第一个参数是 page 呢? - Murhaf Sousli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接