如何在Angular2中使用httpparamserializer [英] How to use httpparamserializer in Angular2
本文介绍了如何在Angular2中使用httpparamserializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Angular2中使用httpparamserializer.我在Google上搜索了很多,但示例仅适用于angular1,如下所示. 如何注入$ httpParamSerializer用于templateUrl
I am trying to use httpparamserializer in Angular2. I googled a lot but the examples are only for angular1 as shown below. How to inject $httpParamSerializer for use in templateUrl
在Angular2中使用它的语法是什么?
What would be the syntax to use it in Angular2?
推荐答案
我有完全相同的问题 此处 >
I had the exact same question HERE
我的解决方案:我有一个POST,在其中将数据发布到Web服务,并序列化对象,这就是我的方法.它非常简单易用.
My Solution: I have a POST where I post data to a web service and I serialize my object this is how I do it. It is pretty simple and easy to use.
基本示例
let params = new URLSearchParams();
params.set('search', term); // the user's search value
my-form-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;
}
这篇关于如何在Angular2中使用httpparamserializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文