2016-09-18 4 views
1

サービスを使用して非同期httpコールを作成する単純なコントローラを設定しようとしています。私は書いた別のコントローラーと非常によく似たものをセットアップしましたが、何らかの理由でこれが機能していません。 console.log($ scope.art); then()ブロックの行は正しいデータを出力しますが、then()ブロックの外に出ると$ scope.artは未定義です。これはなぜでしょうか?私は非常に混乱しています!

app.controller('FeedbackController', ['$scope','getArt', function($scope, getArt) { 
     var art = getArt(); 
     art.then(function(result) { 
      $scope.art = result; 
      console.log($scope.art); 
     }, function(reason) { 
      $scope.error = reason; 
     }); 
     console.log($scope.art); 
}]) 
.factory('getArt', ['$http', '$q', function($http, $q) { 
    return function() { 

     var deferred = $q.defer(); 
     $http.post("/php/getArt.php") 
      .success(function (response) { 
       if (response == "nope") { 
        deferred.reject("Whoopsie! Something seems to have gone wrong."); 
       } else { 
        deferred.resolve(response); 
       } 
      }) 
      .error(function() { 
       deferred.reject("There seems to be an issue with your connection."); 
      }); 
     return deferred.promise; 
    }; 
}]); 

ありがとうございます!

答えて

0

httpコールは非同期です。したがって、console.log($scope.art);を実行してから、httpコールが終了しました。 thenコールバックで後処理を行うことができます。

また、ユーザーのためにartオブジェクトを表示する必要がある場合は、サーバーによってdatが返されるとすぐに表示されます。たぶん、あなたはそのデータを示すために、このようなものを追加することができ、サーバからロードbeeingてさ:9行目は、右の直後に実行されます

app.controller('FeedbackController', ['$scope','getArt', function($scope, getArt) { 
    var art = getArt(); 
    art.then(function(result) { 
     $scope.art = result; //line 4, executed some time in the future 
     console.log($scope.art); //line 5 
    }, function(reason) { 
     $scope.error = reason; 
    }); 
    console.log($scope.art); //line 9, synchronously, executed right away 
}]) 

次のコードで

<div ng-if="!art">loading...</div> 
 
<div ng-if="art">... display it for the user ...</div>

+0

ああうわあ、私は馬鹿だルイーズ非同期(async)JavaScriptを説明する記事です!それはたくさんの意味があります。ありがとうございました! –

+0

Wellcome to javascript&async @CarterScottDavis :) –

関連する問題