簡體   English   中英

使用promises的$ scope問題

[英]Issue with $scope using promises

我正在嘗試設置一個簡單的控制器,使用服務進行異步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;
   };
 }]);

非常感謝你!!

http調用是異步的,因此你是console.log($scope.art); http調用結束之前執行。 您可以在then回調中進行任何后處理。

或者,如果您只需要為用戶顯示art對象,則只要服務器返回dat,它就會出現。 也許你可以添加這樣的東西來表明從服務器加載數據:

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

在以下代碼中

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
}])

在調用服務器之后立即執行第9行,這是在第4行和第5行之前(當履行承諾時),所以當發生這種情況時,$ scope.art仍然是未定義的 (或者仍然有一些舊的值)

作為參考,這里有一篇很好地解釋JavaScript異步的文章http://tutorials.pluralsight.com/front-end-javascript/introduction-to-asynchronous-javascript

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM