角 - 使用Restangular时,放弃Ajax请求 [英] Angular - abort ajax request when using Restangular

查看:253
本文介绍了角 - 使用Restangular时,放弃Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用一个角度的服务,从而使通过服务一个Ajax请求的方法。我需要确保,如果这就是所谓的好几倍,在中止(如果它尚未解决的即是)在previous请求。

I have a method that calls an angular service and consequently makes an ajax request via the service. I need to make sure that if this is called several times, the previous request in aborted (if it hasn't already been resolved that is).

此方法可以得到多次调用。这种方法实际上是从ngTable是 ngTableParams

This method can get called multiple times. This method is actually from ngTable on ngTableParams:

getData = function($defer, params) {

      myService.getRecord(params).then(function(res){ 
             ...
             $defer.resolve(res.Records);
      }); 
}

下面是关于服务的方法:

Here's the method on the service:

this.getRecords = function(params) {
    ...

    return Restangular
          .all('/api/records')
          .post(filters);
};

如果ngTable使得3个电话我希望第一个2中止(当然,除非他们返回如此之快,它得到了解决)

If ngTable makes 3 calls I want the first 2 to be aborted (unless of course they returned so fast that it got resolved)

推荐答案

可以中止 $ HTTP 通过超时通话配置属性,它可以是一个承诺,即中止解决当请求。

You can abort $http calls via the timeout config property, which can be a Promise, that aborts the request when resolved.

因此​​,在restangular,你可以做到这一点像

So in restangular, you can do this like

var abort = $q.defer();
Restangular.one('foos', 12345).withHttpConfig({timeout: abort.promise}).get();
abort.resolve();

要它与你的用例整合,例如,你可以在你的服务有这样的:

To integrate it with your usecase, for example, you could have this in your service:

var abortGet;

this.getRecords = function(params) {
  ...
  if (abortGet) abortGet.resolve();
  abortGet = $q.defer();
  return Restangular
    .all('/api/records')
    .withHttpConfig({timeout: abortGet.promise})
    .post(filters);
}

这三方通话 getRecords 总是中止previous呼叫如果尚未解决!

This way calling getRecords always aborts the previous call if has not been resolved yet!

希望这有助于!

这篇关于角 - 使用Restangular时,放弃Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆