Created
April 27, 2016 14:21
-
-
Save karlr42/f566405cf7c59319cd2fe31c3d2d9a85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.service("HttpParamSerializerPolyfillService", function() { | |
/** | |
* Adapation of the souce of $httpParamSerializer | |
* so it can be used with angular < 1.4 | |
* | |
* HttpParamSerializerPolyfillService.serialize(query) | |
* | |
* No guarantees or warranty, use at your own risk. | |
*/ | |
function sortedKeys(obj) { | |
return Object.keys(obj).sort(); | |
} | |
function forEachSorted(obj, iterator, context) { | |
var keys = sortedKeys(obj); | |
for (var i = 0; i < keys.length; i++) { | |
iterator.call(context, obj[keys[i]], keys[i]); | |
} | |
return keys; | |
} | |
function encodeUriQuery(val, pctEncodeSpaces) { | |
return encodeURIComponent(val). | |
replace(/%40/gi, "@"). | |
replace(/%3A/gi, ":"). | |
replace(/%24/g, "$"). | |
replace(/%2C/gi, ","). | |
replace(/%3B/gi, ";"). | |
replace(/%20/g, (pctEncodeSpaces ? "%20" : "+")); | |
} | |
function serializeValue(v) { | |
if (isObject(v)) { | |
return angular.isDate(v) ? v.toISOString() : angular.toJson(v); | |
} | |
return v; | |
} | |
function isUndefined(value) { return typeof value === "undefined"; } | |
var isArray = Array.isArray; | |
function isObject(value) { | |
// http://jsperf.com/isobject4 | |
return value !== null && typeof value === "object"; | |
} | |
this.serialize = function(params) { | |
if (!params){ | |
return ""; | |
} | |
var parts = []; | |
forEachSorted(params, function(value, key) { | |
if (value === null || isUndefined(value)){ | |
return; | |
} | |
if (isArray(value)) { | |
angular.forEach(value, function(v, k) { | |
parts.push(encodeUriQuery(key) + "=" + encodeUriQuery(serializeValue(v))); | |
}); | |
} else { | |
parts.push(encodeUriQuery(key) + "=" + encodeUriQuery(serializeValue(value))); | |
} | |
}); | |
return parts.join("&"); | |
}; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment