簡體   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