【问题标题】:Ensure the proper order of subsequent HTTP ajax calls in AngularJS确保 AngularJS 中后续 HTTP ajax 调用的正确顺序
【发布时间】:2014-10-25 03:20:00
【问题描述】:

假设我们有一个超级简单的带有自动完成功能的搜索表单,它会在 keyup/keypress 上触发 $http.get() 请求:

<input type="text" ng-model="keyword" ng-change="makeRequest()">

$scope.makeRequest = function() {
   $http.get(url).then(function(res) {
      // update the typeahead list here.
   });
}

保持响应传递顺序的最简单方法是什么?由于延迟不同,较早的结果通常排在最后,这使用户感到困惑。 我正在寻找一种顺序而不是直接去抖动,它会阻止在某个击键间隔下发出请求。

【问题讨论】:

    标签: javascript ajax angularjs angularjs-service


    【解决方案1】:

    您可以跟踪最新的请求并忽略响应,除非它来自最新的...

    var latestRequest = 0;
    $scope.makeRequest = function() {
       var thisRequest = ++latestRequest;
       $http.get(url).then(function(res) {
          if (thisRequest === latestRequest) {
            // update the typeahead
          }
       });
    }
    

    【讨论】:

    • 我认为这是结合时间间隔检查的最简单和最直接的方法(只是让 API 休息一下)。最终检查 params 中的最新关键字,而不是查询计数本身:$http.get(url, params).then(function(res.data) { if(params.keyword === latestKeyword) { $scope.results = res.data });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    相关资源
    最近更新 更多