Skip to content

Instantly share code, notes, and snippets.

@paritosh64ce
Last active November 12, 2017 10:51
Show Gist options
  • Save paritosh64ce/705a06642336a0629fecb8c93dae02a4 to your computer and use it in GitHub Desktop.
Save paritosh64ce/705a06642336a0629fecb8c93dae02a4 to your computer and use it in GitHub Desktop.
Example - Angular 1.x controller calling data service which in turn calls custom common HTTP service
angular.module('myModule')
.service('myAuthSvc', ['$http', '$q', function($http, $q){
var loggedInUserDetails = null;
this.getLoggedInUserDetails = function(payload) {
var deferred = $q.defer();
if(loggedInUserDetails != null) { deferred.resolve(loggedInUserDetails); }
else{
$http.post('<loginURL>', /*payload for login*/)
.then(function(result){
loggedInUserDetails = result;
deferred.resolve(result);
});
}
return deferred.promise;
}
}]);
angular.module('myModule')
.service('myHTTPSvc', ['$http', '$q', 'myAuthSvc', function($http, $q, myAuthSvc){
this.get = function(url, payload, header) {
var deferred = $q.defer();
myAuthSvc.getLoggedInUserDetails()
.then(function(data){
var loggedInUserDetails = data;
var headers = {
'license': loggedInUserDetails.licenseInfo
};
//here you make the actual HTTP call
$http.get(url, payload, headers)
.then(function(result){
deferred.resolve(result);
}, function(error){
deferred.reject(error);
});
});
return deferred.promise;
}
}]);
angular.module('myModule')
.service('orderSvc', ['myHTTPSvc', function(myHTTPSvc){
this.loadOrders = function(payload) {
// myHTTPSvc will add required headers for the HTTP server
return myHTTPSvc.get('<loadOrderURL>', payload);
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment