簡體   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