簡體   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