您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Angular中阻止多个$ http请求。有没有更好的办法?

在Angular中阻止多个$ http请求。有没有更好的办法?

首先,我认为没有必要将其包装HttpPromise到另一个承诺中。在不赞成使用success/error方法的情况下,您应该仅依靠该方法,并将当作常规承诺。then()``HttpPromise

为了确保只发送一次请求,您实际上可以跟踪HttpPromise创建的第一个请求,并在随后的函数调用中返回相同的promise。

这是一项服务,它将接受API端点作为参数,并确保仅向该API发送一个请求。

app.factory('$httpOnce', [ '$http', '$cacheFactory',
  function ($http, $cacheFactory) {
    var cache = $cacheFactory('$httpOnce');

    return function $httpOnce(url, options) {
      return cache.get(url) || cache.put(url, $http.get(url, options)
        .then(function (response) {
          return response.data;
        }));
    };
  }
]);

function log(data) {
  console.log(data);
}

// issues an HTTP request
$httpOnce('https://api.github.com/').then(log);
// does not issue an HTTP request, returns the same promise as above
$httpOnce('https://api.github.com/').then(log);

// ...
// HTTP request completes somewhere, both promises above are resolved
// ...

setTimeout(function () {
  // immediately resolved
  $httpOnce('https://api.github.com/').then(log);
}, 5000);

这是一个演示。您可以在开发工具中看到仅发出一个请求。

其他 2022/1/1 18:14:05 有669人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶