如何将URL参数(查询string)传递给Angular 2上的HTTP请求

嗨,大家好我在Angular 2创build一个HTTP请求,但我不知道如何添加url参数(查询string)。

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

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

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

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

然后只是Http模块做这个工作,把它parsing成URL查询string。

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

该对象的search字段可用于设置string或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类的文档有更多的细节。 它可以在这里find。

编辑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.search已被弃用。 改用requestOptions.params

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

原始答案(Angular 2)

您需要导入URLSearchParams如下

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

然后build立你的参数,并使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()) ... 

版本4.3.x +

@ angular / common / 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}); 

可以帮助一些!

我的例子

 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 

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

零件

 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 }); }); }); 
 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和包括在angular-cli.json