简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM