POST时,Angular GET请求不会中止

时间:2015-07-21 15:30:22

标签: angularjs http ionic angular-services

我已经为api请求写了一个有角度的服务/工厂,有一个有get请求,另一个有post请求。我的行为非常奇怪。

我无法使用以下代码取消/中止GET请求,并且GET请求运行完成而不会被取消。

var joblist = jobsService.getJobList($scope.jobListData);
joblist.then($scope.jobListSuccess,$scope.jobListError);
joblist.abort('cancelling get request');

但我可以使用以下代码取消/中止POST请求,它将被取消并返回http状态代码0,这就是我想要的。

var addNewJob = jobsService.addJob($scope.addNewJobData);
addNewJob.then($scope.addNewJobSuccess,$scope.addNewJobError);
addNewJob.abort('cancelling post request');

我想知道为什么当POST请求使用类似的代码中止/取消时,GET请求不会中止/取消。

.factory('jobsService',function($ http,$ q,API_URL_PREFIX){

//return job list
this.getJobList = function(data){

    var deferredAbort  = $q.defer();

    // Initiate the AJAX request.
    var request = $http({
        method: 'get',
        url: API_URL_PREFIX + 'jobs',
        params : data,
        timeout: deferredAbort.promise
    });

    var promise = request.then(
        function( response ) {
            return( response.data );
        },
        function() {
            return( $q.reject( 'Something went wrong' ) );
        }
    );

    promise.abort = function(reason) {
        console.log(reason);
        deferredAbort.resolve();
    };

    promise.finally(
        function() {
            promise.abort = angular.noop;
            deferredAbort = request = promise = null;
        }
    );

    return( promise );
}

//add job
this.addJob = function(data){

    var deferredAbort  = $q.defer();

    // Initiate the AJAX request.
    var request = $http({
        method: 'post',
        url: API_URL_PREFIX + 'jobs',
        data: data,
        timeout: deferredAbort.promise
    });

    var promise = request.then(
        function( response ) {
            return( response.data );
        },
        function() {
            return( $q.reject( 'Something went wrong' ) );
        }
    );

    promise.abort = function(reason) {
        console.log(reason);
        deferredAbort.resolve();
    };

    promise.finally(
        function() {
            promise.abort = angular.noop;
            deferredAbort = request = promise = null;
        }
    );

    return( promise );
}


// Return the public API.
return({
    getJobList: this.getJobList,
    addJob: this.addJob
});

});

0 个答案:

没有答案