realph
realph

Reputation: 4671

Angular JS: Service Response not Saving to Variable

I'm trying to work out why the response of this service isn't saving to $scope.counter. I've added a function to my service fetchCustomers(p) which takes some parameters and returns a number, which I'd like to save to $scope.counter.

service

angular.module('app')
.factory('MyService', MyService)

function MyService($http) {
  var url = 'URL'';

  return {
    fetchTotal: function(p) {
      return $http.get(url, { params: p })
        .then(function(response) {
          return response.data.meta.total;
        }, function(error) {
          console.log("error occured");
        })
    }
  }
}

controller

$scope.counter = MyService.fetchTotal(params).then(function(response) {
  console.log(response);
  return response;
});

For some reason though, this isn't working. It's console logging the value, but not saving it to $scope.counter. Any ideas?

Upvotes: 0

Views: 780

Answers (1)

Jeff
Jeff

Reputation: 2068

If I understand your question correctly, you're setting $scope.counter to a promise, not the response.

MyService.fetchTotal(params).then(function(response) {
  // Anything dealing with data from the server
  // must be put inside this callback
  $scope.counter = response;
  console.log($scope.counter); // Data from server
});

// Don't do this
console.log($scope.counter); // Undefined

Upvotes: 3

Related Questions