Created
October 15, 2013 22:10
-
-
Save kapv89/6999460 to your computer and use it in GitHub Desktop.
a jquery.ajax based replacement for angular http layer
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
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