Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何覆盖angularjs中的$http对象_Angularjs_Rest - Fatal编程技术网

如何覆盖angularjs中的$http对象

如何覆盖angularjs中的$http对象,angularjs,rest,Angularjs,Rest,我在angular js中使用&http进行REST调用。当我打一个新电话时,我想取消前一个电话。因此,我将数据调用包装在服务中,并调用控制器中的服务。我使用全局参数保存最后一个调用对象。因此,每当我调用函数getsth时,它都会用新的函数替换上次调用。但当我调试时,它确实用新的调用替换了最后一个调用,但前一个调用仍然会触发。一个解决方案是取消前一个电话,我尝试了它的工作。但是我的问题是我是否可以覆盖$http对象,这样我就不必处理它了。谢谢 控制器: var lastCall; $scope.

我在angular js中使用&http进行REST调用。当我打一个新电话时,我想取消前一个电话。因此,我将数据调用包装在服务中,并调用控制器中的服务。我使用全局参数保存最后一个调用对象。因此,每当我调用函数getsth时,它都会用新的函数替换上次调用。但当我调试时,它确实用新的调用替换了最后一个调用,但前一个调用仍然会触发。一个解决方案是取消前一个电话,我尝试了它的工作。但是我的问题是我是否可以覆盖$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);
}

这篇博客文章很好地解释了您的用例:


您可以添加装饰器或拦截器。。。完全覆盖对象将是一个极其可怕的想法。@DanPantry Thant是真的。我决定对$http使用取消功能。谢谢,我在我的服务中实现了cancel功能,它工作正常。我只是想知道有没有更好的方法克服$http对象在我看来是一件非常痛苦的事情,所以我不认为有更好的方法。很抱歉
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);
    };
});