-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

あなたが書くとき

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

プログラムでは、コードの残りの部分に約束して実行を継続するように求めています。この場合、リクエストからのレスポンスを待たずにメソッドconsole.log($scope.weatherResult); の直後に実行されます。$http.get()http

したがって、console.log($scope.weatherResult);API 応答が受信される前でも実行されます。

$scope.weatherResultは内部で定義されていることに注意してください。したがって.success()、応答が成功するまで、Angular はそれについて何も知らない$scope.weatherResultため、コンソールは を返しますundefinedundefinedの場合でも同様となりますerror

successサーバーの応答を表示するには、ブロック内でログに記録できます。

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

于 2014-12-18T18:03:42.980 に答える
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非同期呼び出し?

$watch を使用して通知を受けることができます。

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