title: Best practices to write lazy ajax services
body: <p>What is the best practice to write lazy ajax services in angular-js? For example, I want to create resource that for some reason should return promise like this:</p>
  
  <pre><code>angular.module('MyModule',[])
    .factory('myService', function() {
      return {
        getData: function() {
            return $http.get('http://host/api/data');
        }
      }
    });
  </code></pre>
  
  <p>And I want to load this data only once, so what is the best way to implement it?
  I have only one idea and it is really ugly:</p>
  
  <pre><code>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
      })
  });
  </code></pre>
  
  <p>I don't like this part:</p>
  
  <pre><code>var def = $q.defer();
  def.resolve(dataResponse);
  return def.promise;
  </code></pre>
  
  <p>and also I don't like the fact that I have to write response setter every time I call getter, but I really have no idea how to make this code better.</p>