使用$q.all()从AngularJS中的函数获取$http数据

Getting $http data from functions in AngularJS with $q.all()

本文关键字:函数 获取 http 数据 all 使用 AngularJS      更新时间:2023-09-26

这应该很容易,但我似乎无法让它发挥作用。我有下面的代码,它们基本上是使用$http获取数据的。

仅供参考,我使用的是POST而不是GET。

现在他们并行运行。一个可能在另一个之前完成。我的目标是在全部完成后呈现数据。所以我读了$q,但我似乎无法让它发挥作用。

    $scope.getRestOpen = function () {
    $http({
        method: 'post',
        url: "http://www.xxx.co.uk/php/xxx/restopen-get.php",
        data: $.param({ 'location' : $scope.l, 
                       'time' : $scope.t,
                       'day' : $scope.d,
                       'type' : 'get_restopen' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.open = response.data.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        $scope.open = [];
    });
}
$scope.getRestClosed = function () {
    $http({
        method: 'post',
        url: "http://www.xxx.co.uk/php/xxx/restclosed-get.php",
        data: $.param({ 'location' : $scope.l, 
                       'time' : $scope.t,
                       'day' : $scope.d,
                       'type' : 'get_restclosed' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.closed = response.data.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        $scope.closed = [];
    });
}

正如您所看到的,我可以从主函数本身的$http调用中获得返回的数据;$scope.closed = response.data.data;$scope.open = response.data.data;

但在两者都完成之前,我不想将它们分配给$scope。因此,我应该能够使用$q来完成以下操作,但我的$scope中没有数据,也没有错误。

$q.all([$scope.getRestOpen, $scope.getRestClosed]).then(function(data){
    $scope.open = data[0].data; // doesn't work
    $scope.closed = data[1].data // doesn't work
});

我做错什么了吗?

您需要让$q.all()数组中的每个项都返回一个promise。因为没有返回任何内容,所以您的响应将是[undefined, undefined]

您所需要做的就是用return response.data.data;替换$scope.open = response.data.data;,它应该可以工作。确保在捕捉块中执行相同的操作。

编辑:以下是代码的外观

$scope.getRestOpen = function () {
    return $http({
        method: 'post',
        url: "http://www.xxx.co.uk/php/xxx/restopen-get.php",
        data: $.param({ 'location' : $scope.l,
                'time' : $scope.t,
                'day' : $scope.d,
                'type' : 'get_restopen' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        return response.data.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        return [];
    });
}
$scope.getRestClosed = function () {
    return $http({
        method: 'post',
        url: "http://www.xxx.co.uk/php/xxx/restclosed-get.php",
        data: $.param({ 'location' : $scope.l,
                'time' : $scope.t,
                'day' : $scope.d,
                'type' : 'get_restclosed' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        return response.data.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        return [];
    });
}

像这样修改代码

 $scope.getRestOpen = function () {
    return  $http({
       method: 'post',
       url: "http://www.xxx.co.uk/php/xxx/restopen-get.php",
       data: $.param({ 'location' : $scope.l, 
                   'time' : $scope.t,
                   'day' : $scope.d,
                   'type' : 'get_restopen' }),
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
 }
 $scope.getRestClosed = function () {
    return $http({
      method: 'post',
      url: "http://www.xxx.co.uk/php/xxx/restclosed-get.php",
      data: $.param({ 'location' : $scope.l, 
                   'time' : $scope.t,
                   'day' : $scope.d,
                   'type' : 'get_restclosed' }),
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  });
 }
 $q.all([$scope.getRestOpen(), $scope.getRestClosed()]).then(function(data){
   $scope.open = data[0].data; 
   $scope.closed = data[1].data;
 });

看看这个例子,阅读代码中的注释:

var myApp = angular.module('myApp', []);
function MyCtrl($scope, $q, $timeout) {
    
    var thenFn = function(value) {
        console.log('resolved ', value);
        return value;
    },
    
    q1 = $scope.q1 = $q.defer(),
    q2 = $scope.q2 = $q.defer(),
    p1 = $scope.q1.promise,
    p2 = $scope.q2.promise;
    
    //Wait complete all request 
    $q.all([
        p1.then(thenFn),
        p2.then(thenFn)
    ])
    .then(function(values) {
        $scope.fromThen = values;
    });
    
    // Must start the AngularJS digest process
    // to allow $q.resolve() to work properly
    // So use $timeOut() or $apply()
    
    setTimeout(function() {
        $scope.$apply(function() {
            console.log('resolving delayed promises');
            q1.resolve({
                value: 1
            });
            q2.resolve({
                value: 2
            });
        });
    }, 100, this);
    
    /* 
    *  Alternative approach
    *
    $timeout( function() {
    console.log('resolving delayed promises');
    q1.resolve({value : 1});
    q2.resolve({value : 2});        
});
*/
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
  {{fromThen}}
</div>