Angular 2 http 获取查询字符串参数
Angular 2 http get querystring params
希望有人可以帮助解决这个问题。我构建了一个基于更新的 Angular 2 的 ionic 2 应用程序,我熟悉 Angular 的以前版本,但仍在尝试计算整个打字稿。
我的 API 设置包含基本的获取查询字符串(例如 domain.com?state=ca&city=somename)
export class TestPage {
public state: string ='ca';
public city: string = null;
constructor(private http: Http){}
public submit() {
let url = "http://localhost/api";
let payload = {"state": this.state, "city": this.city};
this.$http.get(url, payload).subscribe(result => {
//result
}, err => {
//do something with the error
}
)
}
}
当我执行此命令时,它会很好地拉动我的 API url,并且我可以获得响应,但是 none 的查询字符串正在请求中发送。它只是发送 http://localhost/api
。如果我 console.log
负载很好。
最终我试图让它完成 https://localhost/api?state=ca&city=example
查看示例,我真的找不到任何直接的东西。
是否无法使用 Angular 的新版本在 http
上加载负载?上面的代码只是一个例子。我有很多查询字符串,这就是我希望向它发送有效负载的原因。
如有任何帮助或建议,我们将不胜感激。
Http.get 方法将实现 RequestOptionsArgs 的对象作为第二个参数。
该对象的搜索字段可用于设置字符串或 URLSearchParams 对象。
一个例子:
// Parameters obj-
let params: URLSearchParams = new URLSearchParams();
params.set('state', this.state);
params.set('city', this.city);
//Http request-
return this.http.get('http://localhost/api', {
search: params
}).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
);
文档:here
希望有人可以帮助解决这个问题。我构建了一个基于更新的 Angular 2 的 ionic 2 应用程序,我熟悉 Angular 的以前版本,但仍在尝试计算整个打字稿。
我的 API 设置包含基本的获取查询字符串(例如 domain.com?state=ca&city=somename)
export class TestPage {
public state: string ='ca';
public city: string = null;
constructor(private http: Http){}
public submit() {
let url = "http://localhost/api";
let payload = {"state": this.state, "city": this.city};
this.$http.get(url, payload).subscribe(result => {
//result
}, err => {
//do something with the error
}
)
}
}
当我执行此命令时,它会很好地拉动我的 API url,并且我可以获得响应,但是 none 的查询字符串正在请求中发送。它只是发送 http://localhost/api
。如果我 console.log
负载很好。
最终我试图让它完成 https://localhost/api?state=ca&city=example
查看示例,我真的找不到任何直接的东西。
是否无法使用 Angular 的新版本在 http
上加载负载?上面的代码只是一个例子。我有很多查询字符串,这就是我希望向它发送有效负载的原因。
如有任何帮助或建议,我们将不胜感激。
Http.get 方法将实现 RequestOptionsArgs 的对象作为第二个参数。
该对象的搜索字段可用于设置字符串或 URLSearchParams 对象。
一个例子:
// Parameters obj-
let params: URLSearchParams = new URLSearchParams();
params.set('state', this.state);
params.set('city', this.city);
//Http request-
return this.http.get('http://localhost/api', {
search: params
}).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
);
文档:here