user3106347 user3106347 - 2 months ago 20
AngularJS Question

Angular reduce api calls

I am creating one sample application, where I have API call for getting classes say

http://localhost:8080/school/4/classes


I have created a service for this

appServices.service( 'classService', ['$http', '$q',
function($http,$q){
this.getClass = function() {

var classes = $q.defer()
$http.get( "http://localhost:8080/school/4/classes" )
.then(function(data) {
classes.resolve(data)
});
return classes.promise
}
}])


I have two controllers say ctrl1 and ctrl2, in both I have code for service as

classService.getClass().then(function(data) {
$scope.classList = data.data.classes
})


My problem is two time api call is happening, can we reduced many api calls to one because my data is not going to be changed. I have already tried with
{ cache: true }
but no luck

Thanks

Answer

The simplest way to prevent multiple calls is to use cache option:

app.service('classService', ['$http', function($http) {
  this.getClass = function() {
    return $http.get('data.json', { cache: true }).then(function(response) {
      return response.data;
    });
  };
}])

Note, that you should not use $q as it's redundant.

In case if you need more control over the cache you can store reference to resolved promise:

app.service('classService', ['$http', function($http) {
  var promise

  this.getClass = function() {
    if (!promise) {
      promise = $http.get('data.json').then(function(response) {
        return response.data;
      });  
    }

    return promise
  };
}]);

And one more pattern with the most flexibility:

app.service('classService', ['$http', '$q', function($http, $q) {
  var data;

  this.getClass = function() {
    return data ? $q.when(data) : $http.get('data.json').then(function(response) {
      data = response.data;
      return data;
    });
  };
}])