AngularJS 等待 ajax 请求完成

AngularJS wait for ajax request to complete

我有一个每 10 秒调用一次的 AJAX 请求,但我希望仅在我之前的请求完成后才能调用 AJAX。

$interval(function () {
            $scope.getContent(2);
        }, 10000);

使用上面的代码,无论我之前的请求是否完成,ajax 请求每 10 秒执行一次。我怎样才能做到这一点?

$interval(function () { if($scope.flag){ $scope.getContent(2); $scope.flag=false; } }, 10000); 并在您之前的请求完成时(即在回调中)将 $scope.flag 值设置为 true

这就是您要实现的目标吗:

DEMO

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $interval, $http, $timeout) {

  // create variable to store interval promise
  var interval;

  $scope.callCount  = 0;
  $scope.pending    = false
  $scope.start      = start;
  $scope.stop       = stop;
  $scope.getContent = getContent;


  function getContent(){

    $scope.pending    = true;
    $scope.callCount  += 1;
    return $http
      .get('foo.json')
      .then(function(response){

        console.log('response', response);

        $scope.pending = false;

        // call stop() if you don't want to 
        // continue calling

        // call stop() then start()
        // if you want to call again
        // immediately and continue calling
        // every 10 seconds

      })
      .catch(function(){
        $scope.pending = false;
      });

    // comment out the $http call above
    // and uncomment the $timeout code
    // below to test that start() does not
    // call getContent() if pending 
    // still true

    // $scope.pending = true;
    // $scope.callCount  += 1;

    // return $timeout(function(){
    //   $scope.pending = false;
    // }, 11000)  

  }

  function start(){

    if(angular.isDefined(interval)) return;

    $scope.getContent();

    interval = $interval(function() {
        if(!$scope.pending){
          $scope.getContent();
        }
    }, 10000);

  }

  function stop(){
    if(angular.isDefined(interval)) {
        console.log('stopping')
        $interval.cancel(interval);
        interval = undefined;
    }
  }

});

html

<body ng-controller="MainCtrl">
    <p>Call Count: {{callCount}}</p>
    <span ng-show="pending">pending...</span>
    <button ng-click="start()">Start</button>
    <button ng-click="stop()">Stop</button>
  </body>