2016-08-25 8 views
0

現在、$ http JSON要求をファクトリの変数に格納し、コントローラ内のその変数の値を取得しようとしています。AJAXの結果をファクトリに格納し、コントローラで取得する

現在、返されるのは未定義です。関数が呼び出される前にAJAXリクエストが終了していないと思います。私はAngularに慣れていないので、私ができる基本的な概念や有用な知識をつかむことを試みています。

app.factory('typiCode', function($http) { 
    var jsonService = { 
     async: function() { 
      var promise = $http.get('https://jsonplaceholder.typicode.com/posts/1') 
      .then(function(response) { 
       console.log(response); 
       return response.data; 
      }) 
      return promise; 
     } 
    }; 
    return jsonService; 
}); 



app.controller("getJson", function($scope, typiCode) { 
    $scope.returnedData = typiCode.jsonService; 
    $scope.logResults = function() { 
     var theData = $scope.returnedData; 
     console.log(theData); 
    } 
}); 

<button ng-click="logResults()">Launch data</button> 

ありがとうございます!

答えて

0

お客様のtypiCodejsonServiceオブジェクトを返します。だからコードのどこかでtypiCode.async()と呼ぶべきです。

あなたのコントローラでは、このように、例えば、行うことができます:

app.controller("getJson", function($scope, typiCode) { 

    typiCode.async() 
    .then(function(data) { 
     $scope.returnedData = data; 
    }) 

    $scope.logResults = function() { 
     var theData = $scope.returnedData; 
     console.log(theData); 
    } 
}); 
+0

これは私が感謝の男:)期待と同じように動作します! –

関連する問題