我正在尝试在Angular2中使用httpparamserializer。我google了很多,但这些例子仅适用于angular1,如下所示。 How to inject $httpParamSerializer for use in templateUrl
在Angular2中使用它的语法是什么?
答案 0 :(得分:10)
我有完全相同的问题HERE
我的解决方案:我有一个POST,我将数据发布到Web服务,并且序列化我的对象,这就是我的工作方式。它非常简单易用。
基本示例
let params = new URLSearchParams();
params.set('search', term); // the user's search value
我外形component.ts 强>
import { Headers, RequestOptions, Http, Response, URLSearchParams } from '@angular/http';
// User is done editing, serialize and POST to web service
saveEdits(): void {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
// Dynamically serialize the entire object
// *** THIS IS THE SERIALIZATION ***
let params: URLSearchParams = this.serialize(this.selectedItem);
this._http.post('http://URLtoPOSTobjTo/path', params, options)
.map(this.extractData)
.catch(this.handleError);
}
/**
* Serializes the form element so it can be passed to the back end through the url.
* The objects properties are the keys and the objects values are the values.
* ex: { "a":1, "b":2, "c":3 } would look like ?a=1&b=2&c=3
* @param {SystemSetup} obj - The system setup to be url encoded
* @returns URLSearchParams - The url encoded system setup
*/
serialize(obj: SystemSetup): URLSearchParams {
let params: URLSearchParams = new URLSearchParams();
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var element = obj[key];
params.set(key, element);
}
}
return params;
}
答案 1 :(得分:0)
deprecated
请参见HttpParams代替URLSearchParams
用法有点棘手,因为HttpParams
是不可变的,因此,如果您想一个接一个地附加许多内容,则必须这样做。
var params = new HttpParams();
params = params.append('foo1', 'bar1');
params = params.append('foo2', 'bar2');