Skip to content

Instantly share code, notes, and snippets.

@georgebrata
Created March 3, 2017 10:09
Show Gist options
  • Save georgebrata/053c6a9fde544d8ac8f53222793635dc to your computer and use it in GitHub Desktop.
Save georgebrata/053c6a9fde544d8ac8f53222793635dc to your computer and use it in GitHub Desktop.
Angular HTTP Service
'use strict';
//ToasterService Dependency
app.factory('HttpService', ['$q', '$http', 'ToastrService', function ($q, $http, ToastrService) {
var HTTP_STATUS_CODES = {
BAD_REQUEST: 400,
NOT_FOUND: 404
};
var request = function (method, url, data) {
var deferred = $q.defer();
var rq = $http({
method: method,
url: url,
data: data
});
rq.then(function (response) {
deferred.resolve(response.data);
}, function(error) {
if (error.status === HTTP_STATUS_CODES.BAD_REQUEST) {
var communicationResult = error.data;
if (communicationResult.errors && communicationResult.errors.length > 0) {
communicationResult.errors.forEach(function (ex) {
if (ex.stackTrace) {
console.error(ex.stackTrace);
}
ToastrService.fail(ex.message);
});
}
if (communicationResult.validationErrors && communicationResult.validationErrors.length > 0) {
communicationResult.validationErrors.forEach(function(ex) {
if (ex.stackTrace) {
console.error(ex.stackTrace);
}
ToastrService.fail(ex.message);
});
}
} else if (error.status === HTTP_STATUS_CODES.NOT_FOUND) {
ToastrService.fail("Server not reachable. Check your internet connection");
}
deferred.reject(error.data);
});
return deferred.promise;
};
var _post = function(url, data) {
return request("post", url, data);
};
var _get = function(url, data) {
//Append current time to the url because the get request are being cached
url = url + (url.indexOf("?") < 0 ? "?t=" : "&t=") + (new Date()).getTime();
return request("get", url, data);
};
return {
post: _post,
get: _get
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment