【发布时间】:2015-12-17 15:26:22
【问题描述】:
我正在尝试构建一个 URL 以从 REST 服务获取数据,有效的 url 应该如下所示
http://SITENAME/api/get_posts/?count=5&page=1&post_type=gallery
我有 count、page、post_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 调试器 => 网络选项卡时,我发现:
但是我没有遇到异常,因为不知何故 url 得到修复并使用有效 url 发送新请求:
问题在于?count=5&page=1 和?&count=5&page=1 之间的区别
这会导致标签微调器卡住并且永远不会结束。
问:为了获得有效的 URL,可以对代码进行哪些改进?
【问题讨论】:
标签: javascript url typescript httprequest