AngularJS:有回调和承诺工作 [英] AngularJS: Working with callbacks and promises

查看:99
本文介绍了AngularJS:有回调和承诺工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法环绕异步请求的概念,我的大脑。

I am unable to wrap my brain around the concept of asynchronous requests.

我有我的看法,这是从供应商创建一个对象实例的控制器:

I have a controller for my view, which is creating an object instance from a provider:

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()对数据的访问。我的方法:

My goal is to get access to the data from Shipment.prototype.fetchShipment() inside my controller. My approach:

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

然而,这将返回undefined。

However, this will return undefined.

我读到q $,并按照,承诺和回调,现在我很喜欢跆拳道;我想要做的是检索的数据推到我的控制器,什么是最好的方式这样做?

I read about $q, and defers, promises and callbacks, and now i am like WTF; all i want to do is to push the retrieved data to my controller, what is the best possible way to do so?

推荐答案

您应该修改code如下图所示,从fetchshipment直接返回的承诺,然后用则()控制器中。

You should modify your code as shown below to return the promise from fetchshipment directly, and then use then() inside your controller.

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

解读code:

调用$ HTTP返回,当你从服务器的数据被解决的承诺。在上面的code,我从它返回一个承诺服务功能回到$ http.post。因此,在控制你在等待的承诺得到解决,并在承诺解决,结果被记录到控制台。

Calling $http return a promise which is resolved when you get the data from the server. In the code above, I have returned $http.post from service function which returns a promise. So in the controller you are waiting for promise to be resolved, and when the promise is resolved, the result is logged to the console.

阅读角上更承诺文档:

  • http://docs.angularjs.org/api/ng.$q
  • http://docs.angularjs.org/api/ng.$http

这篇关于AngularJS:有回调和承诺工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆