多个 $http.get 操作并将信息保存在一个 $scope 变量中

Multiple $http.get operatios and save the information in one $scope variable

我需要执行四个 $http.get 调用,我需要将返回的 $scope 变量发送到一个 HTML 以打印所有信息。目前我在 JS 中有下一个代码:

(function (ng) {

var mod = ng.module("serviciosAdminModule");

mod.controller('serviciosAdminCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get("api/hoteles").then(function (response) {
            $scope.serviciosHotelesRecords = response.data;
        });
    }]);
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get("api/paseos").then(function (response) {
            $scope.serviciosPaseosRecords = response.data;
        });
    }]);
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get("api/aseos").then(function (response) {
            $scope.serviciosAseosRecords = response.data;
        });
    }]);
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get("api/entrenamientos").then(function (response) {
            $scope.serviciosEntrenamientosRecords = response.data;
        });
    }]);

})(window.angular);

在HTML我有下一个:

<tr ng-repeat="servicio in serviciosAdminRecords">
    <td id="{{$index}}-id" class="parrafoscards" style="font-size: 16px">
        <a ui-sref="servicioAdminDetail({servicioId: servicio.id})">{{servicio.id}}</a>
    </td>...

在 HTML 中,我请求 serviciosAdminRecords,它是我想要放置所有 .get 数据的 $scope 变量

您可能需要链接承诺,以便将所有响应一起添加到一个数组中。摆脱所有不同的控制器——它们将有不同的范围——只有一个控制器,通过使用 ng-controller='serviciosAdminCtrl' 作为视图中的属性确保它在视图中使用。

mod.controller('serviciosAdminCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $scope.serviciosAseosRecords = [];
        $http.get("api/hoteles").then(function (response) {
            $scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
            $http.get("api/paseos").then(function (response) {
                $scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
                $http.get("api/aseos").then(function (response) {
                    $scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
                    $http.get("api/entrenamientos").then(function (response) {
                        $scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
                    });
                });
            });
        });
    }]);

如果您的 response.data 是对象数组,则将 serviciosPaseosRecords 初始化为数组。

$scope.serviciosHotelesRecords = [];

而不是将 response.data 分配给 serviciosPaseosRecords

 $scope.serviciosAseosRecords = response.data

Concat response.data 与现有的 serviciosAseosRecords 数组。

$scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data)