简体   繁体   English

$ http POST请求响应在服务中返回JSON对象,但是在Controller中调用时未定义

[英]$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. 几乎我有一个服务,该服务包含通过AngularJS中的$ http服务进行一些REST方法调用的函数。 These methods are then being accessed and called in the Controller. 然后在Controller中访问并调用这些方法。

When the method gets called via the controller the data printed to console in the service is what I expected, the JSON object. 当通过控制器调用该方法时,服务中打印到控制台的数据就是我所期望的JSON对象。 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返回数据。

  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: 但这还不够,因为返回值实际上是$ q Promise ,以使用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);
  };  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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