使用角度2在http GET中传递参数

时间:2016-05-18 05:02:23

标签: angular

如何使用角度2在GET调用中发送参数 我尝试了以下方式,但得到一些错误说,

Argument of type '{ params: URLSearchParams; }' is not assignable to parameter of type 'RequestOptionsArgs'.
  Object literal may only specify known properties, and 'params' does not exist in type 'RequestOptionsArgs'.

函数调用:

import {Http, Response, Headers, RequestOptions, URLSearchParams} from 'angular2/http';
import 'rxjs/Rx';

 constructor(private nav: NavController, public http: Http) {
    onLogin(value: string): void { 
        if(this.authForm.valid) {
          this.userData.login();
          let params = '';
          let options = new RequestOptions({
              // Have to make a URLSearchParams with a query string
              params: new URLSearchParams('validateUsr=false')
          });
          this.http.get('https://itunes.apple.com/us/rss/topmovies/limit=1/json', options)
          .map(res => res.json())
          .subscribe(
            data => {},
            err => this.logError(err),
            () => this.validateUser()
          );

          this.nav.push(AccountViewPage);
        }
      } 

需要传递像这样的参数,

params: {
   validateUsr: "false"
}

2 个答案:

答案 0 :(得分:24)

如果要在GET请求中发送查询参数,请使用search属性而不是params属性:

constructor(private nav: NavController, public http: Http) {
}

onLogin(value: string): void { 
    if(this.authForm.valid) {
      this.userData.login();
      let params = '';
      let options = new RequestOptions({
          // Have to make a URLSearchParams with a query string
          search: new URLSearchParams('validateUsr=false') // <-----
      });
      this.http.get('https://itunes.apple.com/us/rss/topmovies/limit=1/json', options)
      .map(res => res.json())
      .subscribe(
        data => {},
        err => this.logError(err),
        () => this.validateUser()
      );

      this.nav.push(AccountViewPage);
   }
} 

答案 1 :(得分:11)

Thierry's answer很棒,但是如果人们想要创建一个可以接受params的JS对象的函数,我想添加一个扩展选项。在以下函数中,data是可以传递给函数的键/值对的可选JS对象。然后将迭代它,并将每个键/值对添加到URLSearchParams辅助对象(params)。构建params对象后,可以将其作为search对象(RequestOptions)下的options属性传递给GET请求。

handleGet(service:string, data?:any):Observable<any[]> {
    let params = new URLSearchParams();
    for(let key in data) {
        params.set(key, data[key]);
    }
    let options = new RequestOptions({
        search: params
    });
    return this._http.get(service, options)
        .map(this._extractData)
        .catch(this._handleError)
        .finally(() => {
            // do something...
        });
}