Last active
June 6, 2016 00:17
-
-
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
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 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