I wish to convert json object into x-www-form-urlencoded How can I achieve this in angular 2 final release
export class Compentency {
competencies : number[];
}
postData() {
let array = [1, 2, 3];
this.comp.competencies = array;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers, method: 'post' });
return this.http.post(this.postUrl, JSON.stringify(this.comp), options)
.map(res => res.json().data.competencies)
.catch(this.handleError);
}
Assume have an object named postdata as below:
and, you want convert it into x-www-form-urlencoded format, like:
a=1&b=2&c=3
with URLSearchParams it's very easy to do it.
application/x-www-form-urlencoded
Control names and values are escaped. Space characters are replaced by
+', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by
%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e.,%0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by
=' and name/value pairs are separated from each other by `&'.Therefore you will need to transform your JSON object. I would simply iterate over the JSON and output: encodeURIComponent(propertyKey) + "=" + encodeURIComponent(propertyValue) and will combine them using the & sign. e.g.
The non-recursive variant can be expressed as a one-liner with ES6 / TypeScript:
Note that this algorithm (as the other solution as well) makes some assumptions:
use querystring,
npm install querystring
This will convert your json into application/x-www-form-urlencoded