-1

我正在关注使用 $resource 从 API 调用中检索 JSON 数据的 AngularJS 教程。为了便于理解,我尝试将 $resource 代码替换为 $http 代码,但遇到了作用域问题。在结果$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);
4

2 回答 2

1

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

参见例如http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027,或者更好,正如 PSL 所说: 我如何从异步调用?

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

$watch('weatherResult',function(newValue,oldValue)) {
..
}
于 2014-12-18T17:49:07.220 回答
1

当你写

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

在您的程序中,您要求代码的其余部分以承诺继续执行。在这种情况下console.log($scope.weatherResult); ,将在您的$http.get()方法之后执行,而无需等待http请求的响应。

因此,console.log($scope.weatherResult);甚至会在收到 API 响应之前执行。

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

要查看服务器的响应,您可以在success块内很好地记录它。

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

于 2014-12-18T18:03:42.980 回答