AngularJS:使用回调和承诺

时间:2013-07-23 09:15:16

标签: javascript angularjs promise

我无法将我的大脑包围在异步请求的概念中。

我的视图有一个控制器,它正在从提供者创建一个对象实例:

va.controller('VaCtrl',function($scope,$shipment){
    $scope.shipment = $shipment.Shipment();    
});

提供商:

Shipment.provider('$shipment',function(){

    this.$get = function($http){

        function Shipment(){

        }

        Shipment.prototype.fetchShipment = function(){
            var shipment = undefined;
                $http.post('../sys/core/fetchShipment.php',{
                        // some data to POST
            }).then(function(promise){
                    shipment = promise.data;
                });

            return shipment;
        };

        return {
            Shipment: function(){
                return new Shipment();
            }
        }
    }
});

我的目标是从我的控制器中的Shipment.prototype.fetchShipment()访问数据。我的方法:

$scope.fetchShipment = function(){
       var shipment = $scope.shipment.fetchShipment();
        console.log(shipment); // undefined
};

但是,这将返回undefined。

我读了大约$ q,延期,承诺和回调,现在我就像WTF;我想要做的就是将检索到的数据推送到我的控制器,这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:5)

您应该修改您的代码,如下所示直接从fetchshipment返回承诺,然后在您的控制器中使用then()。

Shipment.prototype.fetchShipment = function(){

    return $http.post('../sys/core/fetchShipment.php',{
        // some data to POST
    })
};


$scope.fetchShipment = function(){
    var shipment = $scope.shipment.fetchShipment().then(function(data){;
        console.log(data);
    });
};

代码说明:

调用$ http会返回从服务器获取数据时解析的promise。在上面的代码中,我从服务函数返回$ http.post,它返回一个promise。因此,在控制器中,您正在等待承诺得到解决,并且当承诺得到解决时,结果将记录到控制台。

阅读有关角度的更多承诺文档:

答案 1 :(得分:4)

只是举个例子来说明如何让你的例子与你自己的承诺一起工作。 如果你使用$ http builtin promise会更简单,所以这是一个$ q-example:

angular.module('myApp', []).controller("myAppCtrl", function ($scope, $shipment) {
    $shipment.Shipment().fetchShipment().then(function (shipment) {
        $scope.shipment = shipment
    });
}).provider('$shipment', function () {
    this.$get = function ($http, $q) {

        function Shipment() {

        }

        Shipment.prototype.fetchShipment = function () {
            var defered = $q.defer();
            demodata = {name: "jan", id:8282};
            $http.post('/echo/json/', 'json=' + encodeURIComponent(angular.toJson(demodata)), {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                //resolve promise
                defered.resolve(response.data);
            });

            return defered.promise;
        };

        return {
            Shipment: function () {
                return new Shipment();
            }
        }
    }
});

<div ng-controller="myAppCtrl">{{shipment}}</div>

JSFiddle(使用JSFiddle echo-service作为数据提供者): http://jsfiddle.net/alfrescian/ayke2/

关于承诺的更多信息:

http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/ http://www.egghead.io/video/o84ryzNp36Q AngularJS : Where to use promises? stackoverflow.com/questions/15604196 / ... egghead.io/video/o84ryzNp36Q