$ http.success()内部$ scope的属性在$ http.success()之外未定义。为什么?

时间:2014-12-18 17:43:50

标签: angularjs angularjs-http

我正在关注AngularJS教程,该教程使用$ resource从API调用中检索JSON数据。出于理解的目的,我尝试用$ http代码替换$ resource代码,我遇到了范围问题。在$scope.weatherResult之外记录.success()会产生undefined。为什么会这样?视图接收数据就好了。

另外,

// $scope.weatherAPI = $resource(
     'http://api.openweathermap.org/data/2.5/forecast/daily',
     { callback: 'JSON_CALLBACK' }, { get: { method: 'JSONP' }}
   );

// $scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: 2});


$http.get('
  http://api.openweathermap.org/data/2.5/forecast/daily'
    + '?q='
    + $scope.city
    + '&'
    + 'cnt=2'
  )
  .success(function(data) {
    $scope.weatherResult = data;
  })
  .error(function(error) {
    console.log(error);
  });

console.log($scope.weatherResult);

2 个答案:

答案 0 :(得分:1)

因为$ http是异步的。 $ scope.weatherResult仅在http响应可用时定义。

请参阅示例http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027或更好,因为PSL说:How do I return the response from an asynchronous call?

您可以使用$ watch获取通知:

$watch('weatherResult',function(newValue,oldValue)) {
..
}

答案 1 :(得分:1)

写作时

.success(function(data) { $scope.weatherResult = data; })

在你的程序中,你要求代码的剩余部分继续执行一个promise。 在这种情况下,console.log($scope.weatherResult); 将在$http.get()方法之后执行,而不会等待http请求的响应。

因此,即使在收到API响应之前,也会执行console.log($scope.weatherResult);

请注意,$scope.weatherResult是在.success()内定义的,因此在响应成功之前,Angular不知道$scope.weatherResult,因此控制台会提供undefined。即使是undefined,也会error

要查看服务器的响应,您可以在success块中将其记录好。

.success(function(data) { $scope.weatherResult = data; console.log("$scope.weatherResult = ",$scope.weatherResult); })