如何取消角度服务ajax请求

时间:2015-01-17 08:22:14

标签: angularjs

我有像这样的角度休息服务

.factory('Store', [ '$resource', function($resource) {
        return $resource("/stores/:id/:action.json", {
            id : "@id",
            action : "@action",
            longitude : "@longitude"
        });
    } ])

我在我的控制器中调用get方法,如下所示:

    Store.get({
        id : $stateParams.id,
        longitude: $rootScope.currentLocation.longitude,
        latitude: $rootScope.currentLocation.latitude
    }, function(data) {
        self.original = data;
    }, function(error){
        $rootScope.$broadcast('ServerUnreachable');
    });
};

但是在它解决响应之前,如果用户离开了视图,我想在我的$ destroy回调中取消ajax请求,任何想法?

$scope.$on('$destroy', function() {
    // how to cancel
});

1 个答案:

答案 0 :(得分:2)

$resource documentation说:

  

timeout - {number | Promise} - 超时(以毫秒为单位),或承诺在解决时应中止请求。

因此,将未解决的承诺传递给$ resource调用,并在$ destroy回调函数中解析此未解决的承诺以中止请求:

// create an unresolved canceler
var canceler = $q.defer();
var promiseToPassToResource = canceler.promise;

// to cancel the http call:
canceler.resolve('user left page');