HTTP requests are widely used repeatedly across every web app, so it is wise to write a method for each common request, and then use it in multiple places throughout the app.
Create a httpRequestsService.js
httpRequestsService.js
appName.service('httpRequestsService', function($q, $http){
return {
// function that performs a basic get request
getName: function(){
// make sure $http is injected
return $http.get("/someAPI/names")
.then(function(response) {
// return the result as a promise
return response;
}, function(response) {
// defer the promise
return $q.reject(response.data);
});
},
// add functions for other requests made by your app
addName: function(){
// some code...
}
}
})
The service above will perform a get request inside the service. This will be available to any controller where the service has been injected.
Sample usage
appName.controller('controllerName',
['httpRequestsService', function(httpRequestsService){
// we injected httpRequestsService service on this controller
// that made the getName() function available to use.
httpRequestsService.getName()
.then(function(response){
// success
}, function(error){
// do something with the error
})
}])
Using this approach we can now use httpRequestsService.js anytime and in any controller.