我想从一个Angular组件触发HTTP请求,但我不知道如何向它添加URL参数(查询字符串)。

this.http.get(StaticSettings.BASE_URL).subscribe(
  (response) => this.onGetForecastResult(response.json()),
  (error) => this.onGetForecastError(error.json()),
  () => this.onGetForecastComplete()
)

现在是我的静态设置。BASE_URL就像一个没有查询字符串的URL: http://atsomeplace.com/,但我想让它像http://atsomeplace.com/?var1=val1&var2=val2

如何添加var1,和var2到我的HTTP请求对象作为对象?

{
  query: {
    var1: val1,
    var2: val2
  }
}

然后只有HTTP模块将其解析为URL查询字符串。


当前回答

import ...
declare var $:any;
...
getSomeEndPoint(params:any): Observable<any[]> {
    var qStr = $.param(params); //<---YOUR GUY
    return this._http.get(this._adUrl+"?"+qStr)
      .map((response: Response) => <any[]> response.json())
      .catch(this.handleError);
}

如果你已经安装了jQuery,我做npm I jQuery—保存并包含在应用程序中。angular-cli.json中的脚本

其他回答

在最新的Angular 7/8中,你可以使用最简单的方法:-

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

getDetails(searchParams) {
    const httpOptions = {
        headers: { 'Content-Type': 'application/json' },
        params: { ...searchParams}
    };
    return this.http.get(this.Url, httpOptions);
}

编辑Angular >= 4.3.x

HttpClient是和HttpParams一起引入的。下面是一个使用示例:

import { HttpParams, HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

let params = new HttpParams();
params = params.append('var1', val1);
params = params.append('var2', val2);

this.http.get(StaticSettings.BASE_URL, {params: params}).subscribe(...);

(老答案)

编辑Angular >= 4.x

requestOptions。搜索已弃用。requestOptions使用。改为参数:

let requestOptions = new RequestOptions();
requestOptions.params = params;

原始答案(Angular 2)

您需要导入URLSearchParams,如下所示

import { Http, RequestOptions, URLSearchParams } from '@angular/http';

然后构建参数并像下面这样进行http请求:

let params: URLSearchParams = new URLSearchParams();
params.set('var1', val1);
params.set('var2', val2);

let requestOptions = new RequestOptions();
requestOptions.search = params;

this.http.get(StaticSettings.BASE_URL, requestOptions)
    .toPromise()
    .then(response => response.json())
...

角6

你可以通过使用params传入get调用所需的参数:

this.httpClient.get<any>(url, { params: x });

其中x = {property: "123"}。

对于记录“123”的api函数:

router.get('/example', (req, res) => {
    console.log(req.query.property);
})
import ...
declare var $:any;
...
getSomeEndPoint(params:any): Observable<any[]> {
    var qStr = $.param(params); //<---YOUR GUY
    return this._http.get(this._adUrl+"?"+qStr)
      .map((response: Response) => <any[]> response.json())
      .catch(this.handleError);
}

如果你已经安装了jQuery,我做npm I jQuery—保存并包含在应用程序中。angular-cli.json中的脚本

我的例子

private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});

我的方法

  getUserByName(name: string): Observable<MyObject[]> {
    //set request params
    let params: URLSearchParams = new URLSearchParams();
    params.set("name", name);
    //params.set("surname", surname); for more params
    this.options.search = params;

    let url = "http://localhost:8080/test/user/";
    console.log("url: ", url);

    return this.http.get(url, this.options)
      .map((resp: Response) => resp.json() as MyObject[])
      .catch(this.handleError);
  }

  private handleError(err) {
    console.log(err);
    return Observable.throw(err || 'Server error');
  }

在我的分量中

  userList: User[] = [];
  this.userService.getUserByName(this.userName).subscribe(users => {
      this.userList = users;
    });

由邮递员

http://localhost:8080/test/user/?name=Ethem