1

希望有人可以帮助解决这个问题。我构建了一个基于较新的 Angular 2 的 ionic 2 应用程序,我熟悉 Angular 的早期版本,但仍然试图弄清楚整个打字稿。

我的 API 设置带有基本的 get 查询字符串(例如 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,并且我可以得到响应,但是请求中没有发送任何查询字符串。它只是发送http://localhost/api。如果我console.log有效载荷很好。

最终我试图让它去做https://localhost/api?state=ca&city=example

看例子,我真的找不到任何直接的东西。

http使用这个较新版本的 Angular是不是不可能携带有效载荷?上面的代码只是一个例子。我有很多查询字符串,这就是我希望向它发送有效负载的原因。

任何帮助或建议将不胜感激。

4

1 回答 1

1

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()
 );

文档:这里

于 2017-03-27T10:07:02.433 回答