gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:00:12 26 4
gpt4 key购买 nike

我构建了一个有点复杂的方法来通过 $http 返回资源。

该方法返回一个 promise ,然后检查我的本地缓存是否存在资源。如果是,它将返回缓存的资源,如果不是,它将发出 $http 请求。这在资源被缓存后效果很好,但是我在整个应用程序中有多个函数在加载时命中此方法,并且每个函数都会发出 http 请求,因为资源尚未返回和缓存。

我想出了一个简单的检查来解决这个问题,但我觉得应该有更好的方法。我添加了一个 bool 值,如果该方法正在获取资源,则设置为 true,如果是,我用半秒超时解析该方法,以便为请求提供解析时间。代码如下。

那么,有没有更好的办法呢?

   var schools = [];
var loadingSchools = false;

function getAllSchools(forceUpdate) {
return $q(function (resolve, reject) {
if(loadingSchools) resolve($timeout(getAllSchools, 500));

else{

loadingSchools = true;

if (schools.length && !forceUpdate) {
loadingSchools = false;
resolve(schools);
return;
}

console.log('$http: Getting All Schools - schoolService.js');

$http.get(API_PATH + 'schools_GetAll', {cache:true})
.success(function(result) {
schools = result;
loadingSchools = false;
resolve(schools);
})
.error(function(error) {
schools = [];
loadingSchools = false;
reject(error);
});
}
});
}

最佳答案

首先,我认为没有必要将 HttpPromise 包装到另一个 promise 中。使用 success/error 方法 deprecated ,您应该完全依赖 then() 方法,并将 HttpPromise 视为常规 promise 。

为了确保只发送一次请求,您实际上可以跟踪您创建的第一个 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);

这是一个demo .您可以在开发工具中看到只发出了一个请求。

关于javascript - 在 Angular 中防止多个 $http 请求。有没有更好的办法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32958046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com