Skip to content

Instantly share code, notes, and snippets.

@kapv89
Last active June 6, 2016 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kapv89/5915618 to your computer and use it in GitHub Desktop.
Save kapv89/5915618 to your computer and use it in GitHub Desktop.
As yet untested, ajax service for angular operating on jQuery.ajax to avoid all cross browser hassles
define(function () {
return [
'$rootScope', '$q', 'session',
function ($rootScope, $q, session) {
var ajax = function (options) {
var promise = (function () {
var deferred = $q.defer();
options.success = function (data) {
deferred.resolve(data);
};
options.error = function (res) {
console.log(res);
var data = JSON.parse(res.responseText);
var status = res.status;
if(status === 401 || status === 403) {
$rootScope.$broadcast('auth-failed')
}
deferred.reject({status: status, data: data})
}
options.data = options.data || {};
options.type = options.type || 'GET';
options.dataType = options.dataType || 'json';
options.data[session.keyName()] = session.key();
jQuery.ajax(options);
return deferred.promise
})();
return promise;
};
var methods = ['get', 'put', 'post', 'delete'], l = methods.length, i = 0;
for(;i<l;i++) {
var m = methods[i];
ajax[m] = function (options) {
options.type = m.toUpperCase()
return ajax(options);
}
}
return ajax;
}
]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment