AngularJS $资源使用超时中止异步功能请求

时间:2015-09-17 16:18:29

标签: angularjs asynchronous timeout abort

您好我正在寻找一种方法来中止。$ save()请求。我目前在资源对象上有一个超时(以毫秒为单位),但是它没有按我预期的那样工作。超时将触发curCacheObj上的错误响应。$ x毫秒后保存,但它实际上并没有中止。$ save()方法,它仍然会发布到数据库!所以我在考虑做一些事情:

$timeout(function() {
     // abort .$save() function here
}, 30000);

但是,我似乎找不到实际中止请求的方法。

目前我有以下代码(简化):

app.factory('Post', function($resource) {
  return $resource('http://my_endpoint_here/post', {}, {save: {
        method: 'POST',
        timeout: 5000
        }
   });
});

app.service('scService', function ($window, Post, $cordovaProgress, $cordovaDialogs, $timeout) {
                 if (postCount > 0) {
                    $cordovaProgress.showSimple(false);
                    curCacheObj.$save(function (response) {
                            console.log("Post " + postCount + " sent!");
                        }, function (response) {
                              $cordovaProgress.hide();
                              console.log(curCacheObj);
                              $window.location.href= 'index.html';
                              return;
                        }).then(function() {
                            window.localStorage.removeItem("post" + postCount);
                            postCount --;
                            window.localStorage.setItem("localPostCount", postCount);
                            $cordovaProgress.hide();
                            console.log("this just ran");
                            scService.sendCache();
                        });
                }
                else {              
                    $cordovaProgress.showSuccess(false, "Success!");
                    $timeout(function() {
                      $cordovaProgress.hide();
                      $window.location.href= 'index.html';
                    }, 1500);
                }
});

1 个答案:

答案 0 :(得分:0)

原来我通过将超时设置为50毫秒来创建“人为”错误。我没有意识到Web服务端点如何响应传入的请求。我通过测试连接不良来解决这个问题。通过良好的连接,每次都成功发送。$ save()请求。在。$ save()发送的那一刻,无论超时如何,Web服务都将完成其操作。它只知道一个请求刚进来,所以它完成了它的任务并返回一个成功的响应。然后超时将在app.js内(在50ms内)触发,我的错误逻辑将会运行。

修复此'错误'只需要设置60秒的正确超时。

app.factory('Post', function($resource) {
  return $resource('http://my_endpoint_here/post', {}, {save: {
        method: 'POST',
        timeout: 60000 // prev 50ms during testing
        }
   });
});