如何在Angular中将url参数(查询字符串)传递给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就像一个没有查询字符串的URL: http://atsomeplace.com/,但我想让它像http://atsomeplace.com/?var1=val1&var2=val2

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

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

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

647127 次浏览

< a href = " https://angular。io / api /共同/ http / HttpClient noreferrer“rel = > HttpClient < / >方法允许你在选项中设置参数个数

你可以通过从@angular/common/http包中导入< a href = " https://angular。io / api /共同/ http noreferrer“rel = > HttpClientModule < / >来配置它。

import {HttpClientModule} from '@angular/common/http';


@NgModule({
imports: [ BrowserModule, HttpClientModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}

之后,你可以注入HttpClient并使用它来执行请求。

import {HttpClient} from '@angular/common/http'


@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello \{\{name}}</h2>
</div>
`,
})
export class App {
name:string;
constructor(private httpClient: HttpClient) {
this.httpClient.get('/url', {
params: {
appid: 'id1234',
cnt: '5'
},
observe: 'response'
})
.toPromise()
.then(response => {
console.log(response);
})
.catch(console.log);
}
}

对于版本4之前的angular版本,你可以使用Http服务做同样的事情。

Http.get方法接受一个实现RequestOptionsArgs的对象作为第二个参数。

该对象的搜索字段可用于设置字符串或URLSearchParams对象。

一个例子:

 // Parameters obj-
let params: URLSearchParams = new URLSearchParams();
params.set('appid', StaticSettings.API_KEY);
params.set('cnt', days.toString());


//Http request-
return this.http.get(StaticSettings.BASE_URL, {
search: params
}).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
);

Http类的文档有更多细节。它可以在在这里和一个工作示例在这里中找到。

我的例子

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
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 --save,并包括在angular-cli.json中的apps.scripts

编辑Angular >= 4.3.x

HttpClientHttpParams一起被引入。下面是一个使用示例:

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

如果您计划发送多个参数。

组件

private options = {
sort:   '-id',
select: null,
limit:  1000,
skip:   0,
from:   null,
to:     null
};


constructor(private service: Service) { }


ngOnInit() {
this.service.getAllItems(this.options)
.subscribe((item: Item[]) => {
this.item = item;
});
}

服务

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


getAllItems(query: any) {
let params: URLSearchParams = new URLSearchParams();
for(let key in query){
params.set(key.toString(), query[key]);
}
this.options.search = params;
this.header = this.headers();

继续你的http请求,就像@ethemsulan做的那样。

服务器端路由

router.get('/api/items', (req, res) => {
let q = {};
let skip = req.query.skip;
let limit = req.query.limit;
let sort  = req.query.sort;
q.from = req.query.from;
q.to = req.query.to;


Items.find(q)
.skip(skip)
.limit(limit)
.sort(sort)
.exec((err, items) => {
if(err) {
return res.status(500).json({
title: "An error occurred",
error: err
});
}
res.status(200).json({
message: "Success",
obj:  items
});
});
});

版本5 +

在Angular 5及更高版本中,你可以不必使用HttpParams。您可以直接发送json对象,如下所示。

let data = {limit: "2"};
this.httpClient.get<any>(apiUrl, {params: data});

请注意,数据值应该是字符串,即;{ params: {limit: "2"}}

版本4.3.x +

使用@angular /共同/ http中的HttpParams, HttpClient

import { 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});

另外,尝试使用JSON.stringify()对嵌套对象进行字符串化。

角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 { Http, Response } from '@angular/http';
constructor(private _http: Http, private router: Router) {
}


return this._http.get('http://url/login/' + email + '/' + password)
.map((res: Response) => {
return res.json();
}).catch(this._handleError);

你可以使用官方文档中的Url参数

例如:this.httpClient.get(this.API, { params: new HttpParams().set('noCover', noCover) })

在最新的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/common/http中的HttpParams,并在查询时传递一个字符串。 例如:< / p >
import { HttpClient, HttpParams } from '@angular/common/http';
const query = 'key=value' // date=2020-03-06


const options = {
params: new HttpParams({
fromString: query
})
}

现在在你的代码中

this.http.get(urlFull, options);

这对你有用:)

我希望能帮到你