简体   繁体   中英

$http POST request response returning a JSON object in service, but when called in the Controller it is undefined

So pretty much I have a service that contains functions for making some REST method calls via the $http service in AngularJS. These methods are then being accessed and called in the Controller.

When the method gets called via the controller the data printed to console in the service is what I expected, the JSON object. But once that function returns it's data back to the controller it goes undefined.

I'm not too sure what the reason for this is, and would love some insight into why this is happening, does it have to do with scoping or garbage collection?

Thanks!

So here the Service 'hub'

  this.getAllHubs = function() {
    $http({
      method: 'GET',
      url: 'https://****.com',
    }).then(function successCallback(response) {
      console.log('In hub.js ' + JSON.stringify(response.data));
      this.hubs = response.data;
      return response.data;
    }, function errorCallback(response) {
      // Error response right here
    }); 
  };  

So as expected the first console output prints the object properly

And here is the Controller code

app.controller('HubCtrl', HubCtrl);

HubCtrl.$inject = ['$scope','hub'];

function HubCtrl($scope,hub) {
  $scope.hubs = hub.getAllHubs();
  console.log('In ctrl ' + $scope.hubs);

  $scope.addHub = function(_hub) {
    console.log('In Ctrl ' + _hub);
    hub.addHub(_hub);
  };  
}

You did not return the data from the function this.getAllHubs .

  this.getAllHubs = function() {
    return $http({              // Put a return here
      method: 'GET',
      url: 'https://****.com',
    }).then(function successCallback(response) {
      console.log('In hub.js ' + JSON.stringify(response.data));
      this.hubs = response.data;
      return response.data;
    }, function errorCallback(response) {
      // Error response right here
    }); 
  };  

And that's not enough, because the return value is actually a $q Promise , to use the value of the promise:

function HubCtrl($scope,hub) {
  // getAllHubs() now returns a promise
  var hubsPromise = hub.getAllHubs();

  // We have to '.then' it to use its resolved value, note that this is asynchronous!
  hubsPromise.then(function(hubs){
    $scope.hubs = hubs;
    console.log('In ctrl ' + $scope.hubs);
  });

  $scope.addHub = function(_hub) {
    console.log('In Ctrl ' + _hub);
    hub.addHub(_hub);
  };  
}

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