AngularJS等待ajax请求完成

时间:2015-07-28 11:08:20

标签: ajax angularjs intervals

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

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

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

2 个答案:

答案 0 :(得分:1)

这是你想要实现的目标:

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>

答案 1 :(得分:-1)

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