1

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.

Saksham
  • 9,037
  • 7
  • 45
  • 73
  • Posting code, as usual, would help. But since I doubt angular is sending any request, I don't see how it could cancel it. Post the code. You could also just... test it. – JB Nizet Aug 31 '16 at 18:24
  • I did not post any code as the existing one is working fine for me. I'll do it now – Saksham Aug 31 '16 at 18:38
  • @JBNizet now you might get some hint – Saksham Aug 31 '16 at 18:42
  • 1
    Angular has absolutely no idea of what the GetTeachers() method does. It's your own code in that method that sends an HTTP request, and angular can't cancel it. – JB Nizet Aug 31 '16 at 18:46
  • So what should be the approach to cancel any existing `$http` requests that are in progress by this `ng-change`?? @JBNizet – Saksham Aug 31 '16 at 18:56
  • http://stackoverflow.com/questions/13928057/how-to-cancel-an-http-request-in-angularjs – JB Nizet Aug 31 '16 at 18:57
  • https://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery – Saksham Jun 07 '17 at 13:47

1 Answers1

0

If you might want to close a fired request, you can use the timeout property of the http's config object, giving it a number (milliseconds) or a Promise.

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

And in your service, you might need something like:

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

Whenever you would like to cancel the ongoing request (if it isn't finished yet), just call:

canceler.resolve(); 
cristifilip
  • 143
  • 2
  • 11