angularjs-合并for循环api调用中的数据

时间:2018-10-11 15:18:59

标签: javascript angularjs json api

我有一个API,该API的页面为1-10,并且我想循环浏览页码以进行API调用

app.factory('companies', ['$http', function($http) {
    var i;
    for (i = 1; i < 11; i++) {
        var data = $http.get('https://examplepage.com/wp-json/wp/v2/categories?per_page=50&page=' + i);
        console.log('list', data);
    }
    return data;
}]);

这是我在控制台记录所有10个API调用的数据时得到的结果 JSON data

我试图显示所有数据(名称列表),但似乎只接受了最后一个API调用并显示了它。如何将所有返回的数据组合到一个对象中以显示第1-10页的名称列表?

app.controller('HomeController', ['$scope', 'companies', function($scope, companies) {
    companies.success(function(data) {
        $scope.companies = data;
        console.log('companies', $scope.companies);
    });
}]);

view.html

<div class="container" ng-controller="HomeController">
        <div ng-repeat="company in companies" class="list">
            <a href="#/{{ company.id }}" class="company-name">{{ company.name }}</a>
        </div>
</div>

2 个答案:

答案 0 :(得分:1)

每次调用$ http服务都会返回一个承诺。您需要使用$q.all来巩固承诺:

app.factory('companies', function($http,$q) {
    return { tenPagesPromise: tenPagesPromise };

    function tenPagesPromise () {
        var indices = Array.from({length:10}).map((x,i)=>i);
        var promises = indices.map(i=>pagePromise(i));
        return $q.all(promises).then(responseArray => {
            var dataArray = responseArray.map(x=>x.data);
            return dataArray.reduce((t,x)=>t.concat(x),[]);
        });
    }

    function pagePromise(i) {
        var url = "https://examplepage.com/wp-json/wp/v2/categories";
        var params = { per_page: 50, page: i };
        var config = { params: params }
        promise = $http.get(url,config);
        return promise;
    }
});

用法:

companies.tenPagesPromise.then(data => {
    $scope.companies = data;
}).catch(function(errorResponse) {
    console.log(errorResponse);
});

有关更多信息,请参见AngularJS $q Service API Reference - all

答案 1 :(得分:0)

您需要解决承诺,然后将数据添加到数组中,如下所示:

app.factory('companies', ['$http', function($http) {
    data = []
    for (let i = 1; i < 11; i++) {
        $http.get('https://examplepage.com/wp-json/wp/v2/categories?per_page=50&page=' + i)
          .then( function(resp) {
             console.log(resp.data);
             data.push(resp.data);
           })
    }
    return data;
}]);