angularjs - How to cancel angular $http request 1.5 -


i have tried couple things can't seem cancel http request when function called before previous request finished. i'm using 1.5.7 , every time $scope.glsuggested executed want cancel pending glsuggested.get() requests, tried few things reject $q.defer no luck.

here's got:

// controller. export class budgetcontroller {   constructor ($scope, $q, $timeout, $log, glbudget, glsuggested) {     'nginject';      $scope.glsuggested = function(cat) {       var _getsuggested = glsuggested.get(cat);       _getsuggested.then(function(data) {         $scope.glproducts = data;       }, function(error) {         $scope.budgetdetails = 'error';         $log.log(error);       });     };    } }  // service export class glsuggestedservice {   constructor ($http, $q, $rootscope, $log) {     'nginject';     this.$http = $http;     this.$q = $q;     this.$rootscope = $rootscope;     this.$log = $log;   }    get(category) {      var defer = this.$q.defer();      var headers = {       'access-control-allow-origin': '*',       'content-type': 'application/json'     };      var req = this.$http({       method: 'get',       headers: headers,       url: this.$rootscope.apiurl + '/products/recommend/' + category,       timeout: defer.promise     });      var _log = this.$log.log;      req.success(function(data) {       _log('success!', data, data.id);       return defer.resolve(data);     });      req.error(function(data) {       _log('error!', data);       return defer.reject('error');     });      return defer.promise;    }  } 

since put timeout: defer.promise 1 of options $http request, request won't cancel until defer.promise resolves.

so when put defer.resolve in req.success callback, doesn't make sense because you're trying cancel $http request after completes.

also, $http.get returns promise, there no need return results through promise. in get() method, can return req , handle results in then callback.

you should make method in service returns defer.promise , call method in controller. can resolve promise in controller when want cancel $http request.

sorry, know that's little confusing, let me know if makes sense or if need further explanation.


Comments