首先,我认为没有必要包装HttpPromise
变成另一个承诺。随着success/error
方法已弃用,你应该仅仅依靠then()
方法,并治疗HttpPromise
只是一个常规的承诺。
为了确保请求只发送一次,您实际上可以跟踪第一个HttpPromise
您创建并在随后调用该函数时返回相同的承诺。
这是一项服务,它将接受 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;
}));
};
}
]);
Usage
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);
这里有一个demo。在开发工具中可以看到只发出了一个请求。