Angular $q returning promise multiple $http calls

后端 未结 3 2102
梦毁少年i
梦毁少年i 2021-01-05 07:16

I\'m working on an $http call that loops over each of multiple api\'s and returns all of the data in one object. I usually have the promise ready to resolve when the $http c

3条回答
  •  执念已碎
    2021-01-05 07:58

    $q.all and a map function are what you need here:

    function getSearchData() {
        return {
            // returns a promise for an object like:
            // { abo: resultFromAbo, ser: resultFromSer, ... }
            loadDataFromUrls: function () {
                var apiList = ["abo", "ser", "vol", "con", "giv", "blo", "par"];
    
                return $q.all(apiList.map(function (item) {
                    return $http({
                        method: 'GET',
                        url: '/api/' + item
                    });
                }))
                .then(function (results) {
                    var resultObj = {};
                    results.forEach(function (val, i) {
                        resultObj[apiList[i]] = val.data;
                    });
                    return resultObj;        
                });
            }
        };
    }
    

提交回复
热议问题