0

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?

3
  • Probably just a typo but you have an extra quote around 'URL'' Commented Oct 29, 2015 at 0:04
  • 1
    you're assigning $scope.counter to the returned promise, not the response. Your callback should have the assignment $scope.counter = response Commented Oct 29, 2015 at 0:05
  • Yeah sorry, that's a typo Commented Oct 29, 2015 at 0:05

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

9 Comments

But when I now do a $scope.counter, it comes back as undefined: MyService.fetchTotalCustomers(params).then(function(response) { $scope.counter = response; }); console.log($scope.counter);
console.log(response.data.meta.total) in your service, see if thats undefined.
That logs out the number. This is why it's driving me nuts.
Put this inside the promise callback. .then(function(response) { $scope.counter = response; console.log($scope.counter); }); Notice the console.log() is now inside the promise callback.
As soon as you set $scope.counter in the promise callback, it's available for use in the view. It should be working at this point. Have you tested it? If not, update your question with your HTML markup
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.