【问题标题】:Issue with $scope using promises使用承诺的 $scope 问题
【发布时间】:2016-09-18 05:26:15
【问题描述】:

我正在尝试设置一个使用服务进行异步 http 调用的简单控制器。我为我编写的另一个控制器设置了一些非常相似的东西,但由于某种原因,这个控制器不起作用。 then() 块中的 console.log($scope.art); 行输出正确的数据,但是一旦它超出了 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;
   };
 }]);

非常感谢!!

【问题讨论】:

    标签: javascript angularjs http


    【解决方案1】:

    http 调用是异步的,因此您console.log($scope.art); 在http 调用完成之前执行。 您可以在then 回调中进行任何后处理。

    或者,如果您只需要为用户显示art 对象,它就会在服务器返回数据后立即出现。也许你可以添加这样的东西来表明数据正在从服务器加载:

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

    【讨论】:

    • 天哪,路易丝我是个傻瓜!这很有意义。谢谢!
    • 欢迎使用 javascript 和异步 @CarterScottDavis :)
    【解决方案2】:

    在下面的代码中

    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 仍然是 undefined em>(或仍有一些旧值)

    作为参考,这里有一篇文章很好地解释了 JavaScript async http://tutorials.pluralsight.com/front-end-javascript/introduction-to-asynchronous-javascript

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 2020-12-15
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多