首先,我认为没有必要将其包装
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);这是一个演示。您可以在开发工具中看到仅发出一个请求。



