2013-02-03 14 views
9

私は$ httpを使用しようとしていますが、なぜnullの結果を返すのですか?

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であるものを前に実行される内部(

(あなたはそれが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

関連する問題