猿问

如何将URL参数(查询字符串)传递给Angular上的HTTP请求?

大家好我在Angular上创建HTTP请求,但我不知道如何添加url参数(查询字符串)。


this.http.get(StaticSettings.BASE_URL).subscribe(

  (response) => this.onGetForecastResult(response.json()),

  (error) => this.onGetForecastError(error.json()),

  () => this.onGetForecastComplete()

);

现在我的StaticSettings.BASE_URL就像一个没有查询字符串的网址,如:http://atsomeplace.com/ 但我希望它是http://atsomeplace.com/?var1=val1&var2=val2


哪个var1和var2适合我的Http请求对象?我想像对象一样添加它们。


{

  query: {

    var1: val1,

    var2: val2

  }

}

然后只是Http模块完成工作将其解析为URL查询字符串。


慕尼黑8549860
浏览 1022回答 3
3回答

慕的地6264312

编辑角度> = 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(...);(老答案)编辑角度> = 4.xrequestOptions.search已被弃用。requestOptions.params改为使用: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())...

绝地无双

版本5+使用Angular 5及更高版本,您不必使用HttpParams。您可以直接发送您的json对象,如下所示。let data = {limit: "2"};this.httpClient.get<any>(apiUrl, {params: data});请注意,数据值应为字符串,即; { params: {limit: "2"}}版本4.3.x +使用来自@ angular / common / http的HttpParams,HttpClientimport { HttpParams, HttpClient } from '@angular/common/http';...constructor(private httpClient: HttpClient) { ... }...let params = new HttpParams();params = params.append("page", 1);....this.httpClient.get<any>(apiUrl, {params: params});可能会帮助一些!
随时随地看视频慕课网APP
我要回答