如何覆盖angularjs中的$ http对象

问题描述:

我正在使用& http在角度js中进行REST调用。而当我拨打新电话时,我想解除先前的电话。所以我将数据调用包装在服务中,并在控制器中调用服务。我使用全局参数来保存最后的调用对象。所以每当我调用函数getsth()时,它都会用新函数取代lastcall。但是当我调试时,它确实取代了最后一次调用,但之前仍然触发。一种解决方案是取消之前的通话,我试了一下。但我的问题是我可以覆盖$ http对象,所以我不必处理它。由于

控制器:

var lastCall; 
$scope.getsth = function(){ 
    lastcall = service.datacall(); 
    lastcall.then() 
} 

服务:

service.datacall = function(){ 
    var promises = []; 
    promises.push($http({url:method...}).then(function)) 
    return $q.all(promises); 
} 
+0

可以添加装饰,或inte rceptor ...完全覆盖对象将是一个非常可怕的想法。 – 2015-04-02 17:23:54

+0

@DanPantry Thant是真的。我决定使用$ http的取消功能。谢谢 – Gabriel 2015-04-02 21:06:59

此博文解释了您的使用情况非常好:

http://odetocode.com/blogs/scott/archive/2014/04/24/canceling-http-requests-in-angularjs.aspx

app.factory("movies", function($http, $q){ 
    var getById = function(id){ 
     var canceller = $q.defer(); 

     var cancel = function(reason){ 
      canceller.resolve(reason); 
     }; 

     var promise = 
      $http.get("/api/movies/slow/" + id, { timeout: canceller.promise}) 
       .then(function(response){ 
        return response.data; 
       }); 

     return { 
      promise: promise, 
      cancel: cancel 
     }; 
    }; 

    return { 
     getById: getById 
    }; 
}); 

app.controller("mainController", function($scope, movies) { 

    $scope.movies = []; 
    $scope.requests = []; 
    $scope.id = 1; 

    $scope.start = function(){ 

     var request = movies.getById($scope.id++); 
     $scope.requests.push(request); 
     request.promise.then(function(movie){ 
      $scope.movies.push(movie); 
      clearRequest(request); 
     }, function(reason){ 
      console.log(reason); 
     }); 
    }; 

    $scope.cancel = function(request){ 
     request.cancel("User cancelled"); 
     clearRequest(request); 
    }; 

    var clearRequest = function(request){ 
     $scope.requests.splice($scope.requests.indexOf(request), 1); 
    }; 
}); 
+0

是的,我在我的服务中实现了取消功能,它起作用。我只是想知道有一个更好的方法去做 – Gabriel 2015-04-02 21:06:27

+0

覆盖$ http对象将是一个非常痛苦的事情国际海事组织,所以不,我不认为有一个'更好'的方式。抱歉。 – MrE 2015-04-02 21:49:54