繁体   English   中英

如何在我的情况下发出多个http请求

[英]How to make multiple http requests in my case

我正试图用Angular $资源链接一个承诺。

我有以下工厂:

angular.module('myApp').factory('Product', ['$resource', function ($resource) {
    return $resource(
        '/api/product/:name',
        { name: '@name' },
        { 'getSub': {
                url: '/api/product/getSub/:name',
                method: 'GET'}
         }
    );
}]);

我使用我的产品工厂进行多次查询:

Product.query({'name': name}, function(product) {
     Product.getSub({'name': product.name}, function(subItem) {
         Product.getSub({'name':subItem.name}, function(childItem) {
             //do stuff with child item
         })
     })
})

有一个更好的方法吗? 我觉得嵌套所有这些电话不是最好的做法。

你可以把承诺连在一起!

Product.query({'name': name}).$promise
.then(function(product){
  return Product.getSub({'name': product.name}).$promise;
})
.then(function(subItem){
  return Product.getSub({'name': subItem.name}).$promise;
})
.then(function(item){
  // etc
})

您可以使用异步库的瀑布或自己实现它。
这是您案例的示例代码。

async.waterfall([
    function(callback) {
        Product.query({'name': name}, function(product) {
            callback(null, product);
        })
    },
    function(product, callback) {
        Product.getSub({'name': product.name}, function(subItem) {
            callback(null, product, subItem);
        })
    },
    function(product, subItem, callback) {
        Product.getSub({'name':subItem.name}, function(childItem) {
            var result = {};
            result.childItem = childItem;
            result.subItem = subItem;
            result.product = product;

            callback(null, result);
        })
    }
], function (err, result) {
    //do stuff with result
});

一个有用的解决方案可能使用$ q库

https://docs.angularjs.org/api/ng/service/ $ q

您可以使用方法$ q.all()发送大量请求并只管理一个回调then()或make $ q.defer()并解决拒绝您的承诺。

我目前从移动设备上回答这个问题,我不能举个例子。 对于那个很抱歉。 如果当我回到家时,错误列车仍然试图提供帮助

如果您希望一个接一个地完成请求(就像您在示例中所做的那样),您可以执行这样的递归函数:

在这个例子中,我想上传几个图像(调用http路由):

$scope.uploadImageLayout = function (currentIndex, numberOfItems) {
        if (currentIndex === numberOfItems) {
            // in here you could do some last code after everything is done
        } else {
            Upload.upload({
                url: 'localhost:3000/ficheiros',
                file: $scope.imagesToUpload[$scope.auxIndex].file
            }).success(function (data, status, headers, config) {
                if ($scope.auxIndex < numberOfItems) {
                    $scope.uploadImageLayout(currentIndex + 1, numberOfItems);
                }
            });
        }
    };

你第一次打电话就是这样做的:

$scope.uploadImageLayout(0, $scope.imagesToUpload.length);

在你的情况下它是相同的但不是Upload.upload请求你应该有你的请求并捕获回调函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM