Last active
April 12, 2017 23:50
-
-
Save victormejia/8323868 to your computer and use it in GitHub Desktop.
Simple $http wrapper in AngularJS
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
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