【问题标题】:Cancel a resource request in angular以角度取消资源请求
【发布时间】:2015-06-06 19:16:03
【问题描述】:

我是 Angular 新手,所以我需要详细解决这个问题。我看了很多答案,但不是根据我的情况。

我有一个服务:

function ticketService($resource, globals) {
        return $resource(globals.API_URL+'/tickets/:id', {id: '@id'}, {
            update: {method: 'PUT'}
        });
    }

现在我需要在拨打新电话时取消之前的通话。我需要在这里如何使用 timeout 参数?

在控制器中我像这样调用这个服务:

ticketService.get({group_by: type}, function(data) {
.
.
.
.
});

我需要如何更改我的服务和控制器。

谢谢。

【问题讨论】:

    标签: angularjs angularjs-service angular-promise angularjs-resource angularjs-timeout


    【解决方案1】:

    这个例子是前面的 Stackoverflow 问题也应该适用于您的要求。 $resource 支持 Angular 为其 promise 系统提供的 timeout 功能。

    How to cancel an $http request in AngularJS?

    var canceller;
    
    function ticketService($resource, globals) {
        canceller = $q.defer();
    
        return $resource(globals.API_URL + '/tickets/:id', {
            timeout: canceller.promise,
            id: '@id'
        }, {
            update: {method: 'PUT'}
        });
    }
    
    function cancelRequest() {
        if (canceller) {
            // You could also use a $timeout timer to cancel it
            canceller.resolve('cancelled');
        }
    }
    

    【讨论】:

    • 好的。一个问题,我们如何使用 cancelRequest() 方法?
    • 这个方法可以在你的控制器的任何地方调用,你也可以把它添加到$scope,这样UI就可以有一个ng-click允许用户取消请求。您还可以将canceller 传递给Service method,以便在您的自定义服务中取消逻辑。许多选择/路线去
    • @AdnanAli 欢迎您,如果您能够获得可行的解决方案,请不要忘记接受。
    • 很抱歉挖掘了这个,但AngularJS documentation 严格声明In contrast to $http.config, promises are not supported in $resource。您必须改用cancellable$cancelRequest
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2021-12-30
    • 2021-09-19
    • 1970-01-01
    • 2019-11-21
    相关资源
    最近更新 更多