Skip to content

Instantly share code, notes, and snippets.

@victormejia
Last active April 12, 2017 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save victormejia/8323868 to your computer and use it in GitHub Desktop.
Save victormejia/8323868 to your computer and use it in GitHub Desktop.
Simple $http wrapper in AngularJS
angular.module('app')
.factory('AppSvc', function ($http, $q) {
return {
ajaxRq: function (req, cb) {
var deferred = $q.defer();
$http(req)
.success(function (data, status, headers, cfg) {
if (cb) {
deferred.resolve(cb({
status: status,
data: data
}));
}
else {
deferred.resolve(data);
}
})
.error(function (data, status, headers, cfg) {
deferred.reject({
status: status,
data: data
});
});
return deferred.promise;
}
}
});
// sample service that uses the wrapper
angular.modlue('app')
.factory('DataSvc', function (AppSvc) {
return {
getEvents: function (params) {
return AppSvc.ajaxRq({
url: '',
mehtod: 'POST',
headers: '',
data: JSON.stringify(params)
});
}
}
});
// using it in a controller
angular.module('app')
.controller('AppCtrl', function ($scope, DataSvc) {
var getDataProm = DataSvc.getEvents({});
getDataProm.then(function (res) {
var status = res.status,
$scope.data = res.data
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment