Angularjs how to cancel resource promise when switching routes

后端 未结 5 1891
孤街浪徒
孤街浪徒 2020-11-30 05:00

I\'m just getting my feet wet with Angularjs. I have an issue which I think has something to do with promises.

Let\'s say I load route \'A\' which makes several ajax

5条回答
  •  醉酒成梦
    2020-11-30 05:14

    Checking the docs for $resource I found a link to this little beauty. https://docs.angularjs.org/api/ng/service/$http#usage

    timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.

    I've used it with some success. It go a little something like this.

    export default function MyService($q, $http) {
      "ngInject";
      var service = {
        getStuff: getStuff,
      };
    
      let _cancelGetStuff = angular.noop;
    
      return service;
    
      function getStuff(args) {
        _cancelGetStuff(); // cancel any previous request that might be ongoing.
    
        let canceller = $q( resolve => { _cancelGetStuff = resolve; });
    
        return $http({
          method: "GET",
          url: 
          params: args,
          timeout: canceller
        }).then(successCB, errorCB);
    
        function successCB (response) {
          return response.data;
        }
    
        function errorCB (error) {
          return $q.reject(error.data);
        }
      }
    }
    

    Keep in mind

    1. This assumes you only want the results from the last request
    2. The canceled requests still call successCB but the response is undefined.
    3. It may also call errorCB, the error.status will be -1 just like if the request timed out.

提交回复
热议问题