I have integrated promises ($q) with $http services, this will make code more extensible:
This will be shared service which will be consumed by all modules for executing CRUD operation, Request Type, URL, Parameter Object will be passed to this shared service, so it will make code more maintainable, readable and scalable. If we don’t go through this method then we have to use $http.get() or $http.post method, every where in services files of each module, content negotiation issues can be simply handled over here, If you want to append anything with each URL like ‘Http:\\mydomain\’ then instead of copy it on every service file, just hard-code this thing in this file and append URL from their respective services. We don’t need to mention protocol and host-name now in every URL request.
Factory:
app.factory("webApi", [ '$http', '$templateCache', '$q', function ($http, $templateCache, $q) { return { withParameter: function (methodType, webApiUrl, parameterObject) { var deferred = $q.defer(); $http({ method: methodType, url: window.location.protocol + '//' + window.location.host + window.location.pathname + webApiUrl, data: parameterObject, cache: $templateCache }) .success(deferred.resolve) .error(deferred.reject); return deferred.promise; }, nonParameter: function (methodType, webApiUrl) { var deferred = $q.defer(); $http({ method: methodType, url: window.location.protocol + '//' + window.location.host + window.location.pathname + webApiUrl, cache: $templateCache }) .success(deferred.resolve) .error(deferred.reject); return deferred.promise; }, } } ]);
Controller:
vm.candidates = candidateService.getAllCandidates() .then(function (data) { vm.candidates = data; }) .catch(function (data, status) { console.error('error', response.status, response.data); }) .finally(function () { console.log("finally"); });