Skip to content

Instantly share code, notes, and snippets.

@mrcsparker
Created July 9, 2015 22:46
Show Gist options
  • Save mrcsparker/71587c7eee5cb0a06a8a to your computer and use it in GitHub Desktop.
Save mrcsparker/71587c7eee5cb0a06a8a to your computer and use it in GitHub Desktop.
Raw XHR for Angular
'use strict';
// based on https://github.com/mrjgreen/xhr/blob/master/xhr.js
var xhr = function($q) {
var x = function() {
try {
return new XMLHttpRequest();
} catch (e) {}
try {
return new ActiveXObject("Msxml3.XMLHTTP");
} catch (e) {}
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (e) {}
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (e) {}
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {}
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
return null;
},
encode = function(data) {
if (typeof data === "string") {
return data;
}
var e = encodeURIComponent,
result = '';
for (var k in data) {
result += '&' + e(k) + '=' + e(data[k]);
}
return result.substr(1);
},
request = function(method, url, data, headers) {
var def = $q.defer(),
xhr = x(),
payload = encode(data || {});
if (method === 'GET' && payload) {
url += '?' + payload;
payload = null;
}
xhr.open(method, url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
for (var h in headers || {}) {
xhr.setRequestHeader(h, headers[h]);
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
(xhr.status === 200 ? def.resolve : def.reject)({
data: JSON.parse(xhr.responseText),
status: xhr.status,
headers: xhr.getResponseHeader
});
}
};
xhr.send(payload);
def.abort = xhr.abort;
return def;
};
return {
'get': function(url, data, headers) {
return request('GET', url, data, headers);
},
'post': function(url, data, headers) {
return request('POST', url, data, headers);
},
'put': function(url, data, headers) {
return request('PUT', url, data, headers);
},
'delete': function(url, data, headers) {
return request('DELETE', url, data, headers);
},
// Fake an async call using supplied data
'spoof': function(data, headers, status) {
return Promise().resolve({
data: data,
headers: function(header) {
return headers ? headers.header : null;
},
status: status || 200
});
}
};
};
angular.module('bdbcApp').service('$xhr', xhr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment