只有在字符串不为空的情况下,我才能在URL中插入一个字符串吗?

问题描述 投票:0回答:1

我试图从一个数据库中获取数据。有一些可选的部分,我可以包括使搜索更具体。

我有一个这样的对象。

{
  title: "wonderland",
  aliases: "",
  ...
}

现在我想为GET -Request创建一个URL。

getResults(obj){
    return this.http.get(`${this.url}/title=${obj.title}&aliases=${obj.aliases}`)
}

现在我想放弃这个部分 &aliases=${obj.aliases} 因为如上所述,在这种情况下,属性别名是空的。如果属性标题是空的,我就会想删除掉 title=${obj.title}.

你会怎么做呢?

angular string typescript url get
1个回答
1
投票

试试这个 比你想做的更好

let object = {
  title: "wonderland",
  aliases: ""
}

function addOptionalParameters(urlPath) {
  let count = 0;

  for(let param in object){
    if (object[param]) {
      if (count === 0 ) {
        urlPath = `${urlPath}/${param}=${object[param]}`
      } else {
        urlPath = `${urlPath}&${param}=${object[param]}`
      }
      count ++;
    }
  }

  return urlPath;
}

function getResults(obj) {
  let urlPath = `${this.url}`
  urlPath = addOptionalParameters(urlPath)

  return this.http.get(`${urlPath}`)
}

1
投票

你可以做这样的事情。


getAliasQuery(aliases) {
    if (aliases) return '&aliases=${aliases}';
    return '';
}

getResults(obj){
    return this.http.get(`${this.url}/title=${obj.title}${getAliasQuery(obj.aliases)}`)
}
© www.soinside.com 2019 - 2024. All rights reserved.