【问题标题】:angular manage data of multiple http calls角度管理多个http调用的数据
【发布时间】:2016-09-04 19:56:35
【问题描述】:

在这种情况下我有一个严重的问题。 我通过下面的代码从 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;

        });
    };

有什么想法可以做到这一点吗?

【问题讨论】:

  • 我在工作中使用 $q.all() 来解决所有承诺。不幸的是,我现在无法访问存储库,也没有在家中进行必要的设置来尝试示例。试着朝那个方向看。

标签: javascript angularjs api get


【解决方案1】:

你应该检查$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;
    });
}

【讨论】:

  • 谢谢,去看看。我会告诉你的
猜你喜欢
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多