Skip to content

Instantly share code, notes, and snippets.

@kapv89
Created October 15, 2013 22:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kapv89/6999460 to your computer and use it in GitHub Desktop.
Save kapv89/6999460 to your computer and use it in GitHub Desktop.
a jquery.ajax based replacement for angular http layer
define(function () {
return [
'$rootScope', '$q', 'session',
function ($rootScope, $q, session) {
var ajax = function (options) {
var deferred = $q.defer();
var success = function (data, status, xhr) {
$rootScope.$apply(function () { deferred.resolve({ data: data, status: status, xhr: xhr }); });
};
var error = function (xhr) {
var data = JSON.parse(xhr.responseText);
var status = xhr.status;
console.log(status, data);
if(status === 401 || status === 403) {
$rootScope.$broadcast('auth-failed')
}
$rootScope.$apply(function () { deferred.reject({status: status, data: data, xhr: xhr}); });
}
options.data = options.data || {};
options.type = options.type || 'GET';
options.dataType = options.dataType || 'json';
options.beforeSend = function (xhr) {
xhr.setRequestHeader(session.keyName(), session.key());
};
jQuery.ajax(options).done(success).fail(error);
return deferred.promise
};
var methods = ['get', 'put', 'post', 'delete'], l = methods.length, i = 0;
for(;i<l;i++) {
var m = methods[i];
(function (m) {
ajax[m] = function (options) {
options.type = m.toUpperCase()
return ajax(options).then(function (res) { return res.data; });
}
})(m);
}
return ajax;
}
]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment