繁体   English   中英

使用AngularJS对$ http请求实现延迟($ timeout)

[英]Implementing a delay ($timeout) to a $http request with AngularJS

我有一个特定的函数依赖于(先前执行的)服务,该服务将触发对第三方API的多个查询。 这个API可以取消请求,如果它太快太多了。 有没有办法设置$ http查询的延迟?

这是我的$ http代码:

$scope.getImages = function (title, name) {
  $http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + name + '&album='+ title +'&format=json').
   success(function(data4) {
     $scope.images = data4;
   });
}

编辑根据要求我粘贴我的整个JS(可能我应该从一开始就这样做)

angular.module('myApp', ['ngResource'])

  function Ctrl($scope, $http) {
    var search = function(name) {
      if (name) {
        $http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=5').
          success(function(data3) {
            $scope.clicked = false;
            $scope.results = data3.results;
          });
      }
      $scope.reset = function () {
        $scope.sliding = false;
        $scope.name = undefined;
      }
    }
    $scope.$watch('name', search, true);

    $scope.getDetails = function (id) {
      $http.get('http://api.discogs.com/artists/' + id).
        success(function(data) {
            $scope.artist = data;
        });
      $http.get('http://api.discogs.com/artists/' + id + '/releases?page=1&per_page=10').
        success(function(data2) {
            $scope.releases = data2.releases;
        });
      $scope.clicked = true;
      $scope.sliding = true;
    }


    $scope.getImages = function (title, name) {
        $http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + name + '&album='+ title +'&format=json').
          success(function(data4) {
              $scope.images = data4;
          });
      }


  };

我假设你会想要以某种方式去除你的电话,像这样的简单应该有效。 除非在触发之前再次调用搜索(名称),否则它将每300毫秒进行一次调用。

var debounce = null;

var search = function(name) {
  $timeout.cancel(debounce);

  if (name) {
    debounce = $timeout(function() {
        $http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=5')
             .success(function(data3) {
                 $scope.clicked = false;
                 $scope.results = data3.results;
             });
    },300);
  }
  $scope.reset = function () {
    $scope.sliding = false;
    $scope.name = undefined;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM