Cancelling old requests in ng-change with debounce

时间:2016-08-31 18:20:35

标签: angularjs angular-ngmodel

I have a requirement to fetch data through a web service for the search parameter which I type in a textbox. Currently it is working fine with debounce in ng-model-options and it fires a request after the time I specify.

I couldn't find that does angular cancel the previous incomplete request automatically once a new one is fired.

If not, how should I handle this as each key press will fire a request after the time period I specified.

The HTML is

<input type="text" class="form-control" name="inpTeachers" ng-model="inpTeachers" id="inpTeachers" autocomplete="off" required ng-change="GetTeachers(frmAddSubjectMain)" ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }" placeholder="Ex. Nancy Chang" />

And the method GetTeachers is just a simple method changing some scope variables after a http request.

Should I be cancelling the old http request if another ng-change is fired.

1 个答案:

答案 0 :(得分:0)

如果您可能想要关闭已解雇的请求,则可以使用timeout的{​​{1}}属性,为其提供http's config object(毫秒)或number

Promise

在您的服务中,您可能需要以下内容:

function GetTeachers(frmAddSubjectMain){
  var canceler = $q.defer();
  yourService.retrieveTeachers(canceler).then(function() {
      /* here is your result */
  });
}

每当您想要取消正在进行的请求时(如果尚未完成),请致电:

$http.get('/teachers', {timeout: canceler.promise});
相关问题