Monday, March 20, 2017

Best way to Design http calls in AngularJS

Well, after working for a few years with AngularJS, I have seen that call http methods in Angular is tedious and repetitive task. This is something that should be optimized, as it hardly makes sense to call the same request object again and again. This is what motivated me to write this custom factory which reduces a lot of code.

Let's have a look at the code:


 var httpMethods = peerHealthApp.factory('HttpService',HttpService);

httpMethods.$inject = ['$http', 'SITE_CONFIG'];

function HttpService($http, SITE_CONFIG){
console.log("SITE_CONFIG from Peer Service: " + SITE_CONFIG);
var factory = {
httpGet : function(relativePath,data){
var baseUrl = SITE_CONFIG.baseUrl + relativePath;
var response = $http({
method : 'GET',
url : baseUrl,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data : data
});
return response;

},
httpPost : function(relativePath, data){
var baseUrl = SITE_CONFIG.baseUrl + relativePath;
var response = $http({
method : 'POST',
url : baseUrl,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data : data
});
return response;
}

};

return factory;

}

And the above can be used again and again like the following:


  var data=$.param({
"url":moderatedArticleLink
});
var promiseURLMetaData = HttpService.httpPost("parseUrlMetadata", data);
promiseURLMetaData.then(function (response) {
   var urlMetaData = response.data;
return urlMetaData;
})
.catch(function (error) {
console.log("Something went terribly wrong while trying to get URL Meta Data.");
});
   

No comments:

Post a Comment