【问题标题】:how to send only one request instead of multiple request in angularjs?如何在angularjs中只发送一个请求而不是多个请求?
【发布时间】:2018-11-04 23:26:34
【问题描述】:

我有一个演示,其中用户在输入字段中输入任何内容并将请求发送到服务器。目前,只要用户键入它就会触发请求。 我希望只触发一个请求。 例如,如果我输入 "abc" 它会触发三个请求。这可能是用户不停地输入任何内容吗,一秒后停止我会触发一个请求。

我知道输入可以使用 ng-model-options 指令去抖动: 但它会在给定时间后触发,但我希望用户类型只要不停止,但在停止后触发请求 p>

这是我的代码:

http://plnkr.co/edit/npiA2abAo5SEQFMMpKZO?p=preview

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

app.controller('MainCtrl', function($scope,$http) {
   $scope.name = 'World';


    $scope.keyupevt = function(){
       console.log('xx')
       $http.get("data.json")
            .then(function(response) {
               console.log(response)
            });
    }
});

【问题讨论】:

  • 如果您失去焦点并输入 > 0,您可能会触发它。您还可以设置最小字符限制,并等到您至少达到该限制后再发送请求。

标签: javascript angularjs


【解决方案1】:

使用setTimeout/clearTimeout 实现您自己的去抖动,这样就可以了:

app.controller('MainCtrl', function($scope,$http) {
    $scope.name = 'World';

    var timeout = null;                                // the timeout handle
    $scope.keyupevt = function() {
       clearTimeout(timeout);                          // clear any previous timeout (if null, nothing will happen)

       timeout = setTimeout(function() {               // set a new timeout
           console.log('xx');                          // that will make the request after 1 second
           $http.get("data.json")
             .then(function(response) {
               console.log(response);
           });
           timeout = null;                             // reset timeout (not really necessary but it won't do any harm)
       }, 1000);                                       // the code inside will be called after exactly 1000 ms
    }
});

每次按键按下时,请求将设置为在按键按下事件后 1 秒后发生。如果之前的请求还没有发生,则该请求将被取消,并设置一个新的请求在 1 秒后发生。等等

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多