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
What would be the syntax to use it in Angular2?
I had the exact same question HERE
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.
Basic example
let params = new URLSearchParams();
params.set('search', term); // the user's search value
Set Search Parameters
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;
}
deprecated
Please see the HttpParams as replacement for URLSearchParams
The usage is a bit tricky because the HttpParams
is immutable so if you want to append many things one after another you will have to do it like this.
var params = new HttpParams();
params = params.append('foo1', 'bar1');
params = params.append('foo2', 'bar2');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With