繁体   English   中英

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

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

几乎我有一个服务,该服务包含通过AngularJS中的$ http服务进行一些REST方法调用的函数。 然后在Controller中访问并调用这些方法。

当通过控制器调用该方法时,服务中打印到控制台的数据就是我所期望的JSON对象。 但是一旦该函数将其数据返回给控制器,它就变得不确定。

我不太清楚这是什么原因,并且想了解为什么会发生这种情况,这与范围界定或垃圾收集有关吗?

谢谢!

所以这里的服务“枢纽”

  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
    }); 
  };  

因此,按预期,第一个控制台输出将正确打印对象

这是控制器代码

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);
  };  
}

您没有从函数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
    }); 
  };  

但这还不够,因为返回值实际上是$ 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