What are some efficient ways to create lazy ajax services in angular-js? For instance, I need a resource that returns a promise such as:
angular.module('MyModule',[])
.factory('myService', function() {
return {
getData: function() {
return $http.get('http://host/api/data');
}
}
});
I want to ensure that this data is loaded only once. What would be the best approach to achieve this? The current solution I have seems quite inelegant:
angular.module('MyModule', [])
.factory('myService', function($q) {
var dataResponse = null;
return {
getData: function() {
if (dataResponse) {
var def = $q.defer();
def.resolve(dataResponse);
return def.promise;
}
return $http.get('http://host/api/data');
},
setDataResponse: function(response) {
dataResponse = response;
}
}
})
.controller('MyCtrl', function($scope, myService) {
myService.getData().then(function(response) {
myService.setDataResponse(response);
$scope.data = response.data
})
});
This part doesn't sit well with me:
var def = $q.defer();
def.resolve(dataResponse);
return def.promise;
Additionally, having to set the response every time I call for it is not ideal. Are there better ways to improve this code?