Angular管理多个HTTP调用的数据

angular manage data of multiple http calls

本文关键字:调用 数据 HTTP 管理 Angular      更新时间:2023-09-26

在这种情况下我有一个严重的问题。我通过下面的代码从github API获取数据,但由于github每页只允许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;
        });
    };

有什么想法吗?

你应该查看AngularJS站点中的$q文档。

$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;
    });
}