Skip to content

Instantly share code, notes, and snippets.

@nuryagdym
Last active January 29, 2021 12:41
Show Gist options
  • Save nuryagdym/9fe9ab4b3de3d5738d6f596ecf5db374 to your computer and use it in GitHub Desktop.
Save nuryagdym/9fe9ab4b3de3d5738d6f596ecf5db374 to your computer and use it in GitHub Desktop.
Angular JSON object to query string
import {HttpParams} from "@angular/common/http";
export class QueryStringBuilder {
static buildParametersFromSearch<T>(obj: T): HttpParams {
let params: HttpParams= new HttpParams();
if (obj == null)
{
return params;
}
return QueryStringBuilder.populateSearchParams(params, '', obj);
}
private static populateArray<T>(params: HttpParams, prefix: string, val: Array<T>): HttpParams {
for (let index in val) {
let key = prefix + '[' + index + ']';
let value: any = val[index];
params = QueryStringBuilder.populateSearchParams(params, key, value);
}
return params;
}
private static populateObject<T>(params: HttpParams, prefix: string, val: T): HttpParams {
const objectKeys = Object.keys(val) as Array<keyof T>;
for (let objKey of objectKeys) {
let value = val[objKey];
let key = prefix;
if (prefix) {
key += '[' + objKey + ']';
} else {
key += objKey;
}
params = QueryStringBuilder.populateSearchParams(params, key, value);
}
return params;
}
private static populateSearchParams<T>(params: HttpParams, key: string, value: any): HttpParams {
if (value instanceof Array) {
return QueryStringBuilder.populateArray(params, key, value);
}
else if (value instanceof Date) {
return params.append(key, value.toISOString());
}
else if (value instanceof Object) {
return QueryStringBuilder.populateObject(params, key, value);
}
else if ('undefined' !== typeof value && null !== value){
return params.append(key, value.toString());
}
return params;
}
}
@nuryagdym
Copy link
Author

Usage:

const data = {customUser: {firstName: 'john', lastName: 'doe', address: {street: 'wall street'}}, values: [0,1,2]}`;
let params = QueryStringBuilder.buildParametersFromSearch(data);

this.http.post(API_URL, params);

Posted data will be:
image
or as encoded:
customUser%5BfirstName%5D=john&customUser%5BlastName%5D=doe&customUser%5Baddress%5D%5Bstreet%5D=wall%20street&values%5B0%5D=0&values%5B1%5D=1&values%5B2%5D=2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment