2013-02-03 103 views
9

我想使用$ http,但它爲什麼返回空結果?

angular.module('myApp') 
.factory('sender', function($http) { 
    var newData = null; 
    $http.get('test.html') 
     .success(function(data) { 
      newData = data; 
      console.log(newData) 
     }) 
     .error(function() { 
      newData = 'error'; 
     }); 
    console.log(newData) 
    return newData 
}) 

控制檯說:http://screencast.com/t/vBGkl2sThBd4。爲什麼我的newData首先是null,然後被定義?如何正確地做到這一點?

+0

嘿,如果我的回答是,你是什麼請接受它後,所以它不會永遠留開。乾杯! – GFoley83

回答

5

此JavaScript代碼是異步的。

console.log(newData) 
return newData 

之前裏面有什麼success

newData = data; 
console.log(newData) 

因此,在第一次,newData爲空執行(你將其設置爲null)

而當返回的HTTP響應(內成功),newData獲得了新的價值。

這在Javascript中很常見,你應該在success裏面做所有的工作。

+0

好吧,我明白了。謝謝! – Ilia

20

正如YardenST所說,$http是異步的,因此您需要確保依賴於您的$http.get()返回的數據的所有函數或顯示邏輯得到相應處理。做到這一點的方法之一是利用「承諾」是$http回報:

Plunkr Demo

var myApp = angular.module('myApp', []); 

myApp.factory('AvengersService', function ($http) { 

    var AvengersService = { 
     getCast: function() { 
      // $http returns a 'promise' 
      return $http.get("avengers.json").then(function (response) { 
       return response.data; 
      }); 
     } 
    }; 

    return AvengersService; 
}); 


myApp.controller('AvengersCtrl', function($scope, $http, $log, AvengersService) { 
    // Assign service to scope if you'd like to be able call it from your view also 
    $scope.avengers = AvengersService; 

    // Call the async method and then do stuff with what is returned inside the function 
    AvengersService.getCast().then(function (asyncCastData) { 
      $scope.avengers.cast = asyncCastData; 
    }); 

    // We can also use $watch to keep an eye out for when $scope.avengers.cast gets populated 
    $scope.$watch('avengers.cast', function (cast) { 
     // When $scope.avengers.cast has data, then run these functions 
     if (angular.isDefined(cast)) {   
      $log.info("$scope.avengers.cast has data"); 
     } 
    }); 
}); 
+0

非常感謝! – Ilia

+0

很好的回答!我要添加這個到我的博客! :) –

+0

@ sk8terboi87ツ然後點擊該投票;這是它的目的! :) – GFoley83