You cannot return data in your success
and error
handlers. The $http
call is asynchronous, so the callback functions are called when the promise is resolved...but returning the data to your service after it has run would have no effect.
Instead, consider injecting $http
into your controller and calling it from there.
EDIT
Following up on my comment, $http
itself is a service, so unless you are doing something more than just making a call, it doesn't make sense to wrap it in another service. Just use the $http service in your controller, like this:
angular.module('myApp')
.controller('MyController', MyController);
MyController.$inject = ['$http'];
function MyController($http) {
$http.get('http://path.to.api/')
.then(function(res) { /* handle success */ })
.catch(function(err) { /* handle error */ });
}
However, if you want to provide a service that makes a call and caches the response, you could write a service for that. Something like this...
angular.module('myApp')
.factory('myDataService', myDataServiceFactory);
myDataServiceFactory.$inject = ['$http', '$cacheFactory', '$q'];
function myDataServiceFactory($http, $cacheFactory, $q) {
var cache = $cacheFactory('myData');
return {
getData: getData,
};
function getData(url) {
var data = cache.get(url);
if (data) {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
var promise = $http.get(url);
promise.then(function(res) {
cache.put(url, res);
});
return promise;
}
}
...but that example is kind of silly, because $http
already offers a configuration for caching response data.