角度管理多个http调用的数据

时间:2016-09-04 19:56:35

标签: javascript angularjs api get

在这种情况下,我遇到了严重的问题。 我通过下面的代码从github API获取数据,但由于github alllow每页只有30个结果,我想获取所有数据以获得更好的排序选项并将其推送到一个对象数组。下面找到一个代码 这个工作正常

$scope.getData = function () {
        $http({
            method: "GET",
            url: api url + pageNum
        }).then(function mySucces(response) {
            $scope.mydata = response.data;
            $scope.isLoading = false;
            $scope.result = $scope.mydata.map(function (a) { return { 'name': a.name, 'html_url': a.html_url }; });

        }, function myError(response) {
            $scope.error = response.statusText;

        });
    };

但我想做这样的事情

$scope.getData = function () {
for(var i =0; i<= $scope.pages.length; i++){
        $http({
            method: "GET",
            url: "apiUrl + i
        }).then(function mySucces(response) {
            $scope.mydata = response.data;
            $scope.isLoading = false;
            $scope.result = $scope.mydata.map(function (a) { return { 'name': a.name, 'html_url': a.html_url }; });

        }, function myError(response) {
            $scope.error = response.statusText;

        });
    };

任何想法都可以做到这一点?

1 个答案:

答案 0 :(得分:0)

您应该查看$q documentation in the AngularJS site

$scope.getData = function () {
    $scope.result = [];
    $scope.error = [];
    $q.all($scope.pages.map(function(page) {
        return $http({
            method: "GET",
            url: "apiUrl" + i
        })
        // This function will be triggered when each call is finished.
        .then(function mySucces(response) {
            $scope.mydata.push(response.data);
            $scope.result.push($scope.mydata.map(function (a) { return { 'name': a.name, 'html_url': a.html_url }; }));

        })
    }))
    // This call will be called when all of the calls are finished.
    .then(function(success) {
        $scope.isLoading = false;
    }).catch(function (error) {
        $scope.error = response.statusText;
    });
}