最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS: Working with callbacks and promises - Stack Overflow

programmeradmin3浏览0评论

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

The provider:

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

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

However, this will return undefined.

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?

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

The provider:

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

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

However, this will return undefined.

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?

Share Improve this question edited Jul 23, 2013 at 9:22 user2422960 asked Jul 23, 2013 at 9:15 user2422960user2422960 1,5266 gold badges17 silver badges28 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

Explanation to Code :

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.

Read about more promise documentation on angular:

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

Just the give you an example how to get your example working with your own promise. It's much more simple if you use $http builtin promise, so it's an $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 (use JSFiddle echo-service as data provider): http://jsfiddle/alfrescian/ayke2/

More about promises:

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

发布评论

评论列表(0)

  1. 暂无评论