Created
June 10, 2014 13:56
-
-
Save toddmotto/9ee0abc5c8120e010a27 to your computer and use it in GitHub Desktop.
XHR wrapper for AngularJS $http
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
/** | |
* @name xhr | |
* @desc Dynamic $http/$q | |
* @param {String} [type] HTTP method | |
* @param {Array} config Array of config to be called with .apply() | |
* @private | |
* @returns {Object} deferred.promise | |
*/ | |
var xhr = function (type, config) { | |
if (!config && angular.isArray(type)) { | |
config = type; | |
type = 'get'; | |
} | |
var deferred = $q.defer(); | |
$http[type].apply($http, config) | |
.success(function (data) { | |
deferred.resolve(data); | |
}) | |
.error(function (reason) { | |
deferred.reject(reason); | |
}); | |
return deferred.promise; | |
}; |
Use $q
for promises/defers, but it's also a nicer way (IMO) to resolve the $http
(which would return a promise) but mixing with $q
provides us the pure promise Object and data rather than HTTP crap. We can also use $q.all()
to create an Array of promises too:
$q.all([
promise1.then(something),
promise2.then(somethingElse)
])
.then(function(data) {
// do something with `data`
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Haven't used $q much personally. Could you provide an example of this being used? :)