Angular 有没有办法避免重复 http 请求?
正如您在上面的代码中看到的,我正在拨打电话以检索产品的详细信息。
事实上,这个调用与一个按钮相关联......
我会避免重复打电话。
如果我点击了详细产品按钮,显然我不需要再次调用我的服务......正确的方法是加载信息一次,然后显示和隐藏;但我不知道如何在 Angular 上管理它。
(而且我不想从头开始加载每个产品的详细产品,我只想根据用户的 CLI 需求加载,但一次)
$scope.seeInfo= function(id){
$http.get('/shop/getDetailInfo/'+id).
success(function(data, status) {
$scope.info = data.detailinfo;
if (data.detailinfo>0) $scope.showDetails=true;
else $scope.showDetails=false;
});
};
Angular $http 内置了缓存功能,可能就是您所需要的
https://docs.angularjs.org/api/ng/service/$http https://docs.angularjs.org/api/ng/service/%24http
$scope.seeInfo= function(id){
$http.get('/shop/getDetailInfo/'+id, {cache: true}).
success(function(data, status) {
$scope.info = data.detailinfo;
if (data.detailinfo>0) $scope.showDetails=true;
else $scope.showDetails=false;
});
};
update
我看到你选择了“自己开发”的解决方案,这通常比使用 Angular 提供的解决方案更容易出现错误。
这里如何实现相同的目标:
// access the $http cache
var httpCache = $cacheFactory('$http');
// retrieve an element from cache
var detailInfo = httpCache.get('/shop/getDetailInfo/' + id);
// delete a cache element
httpCache.remove('/shop/getDetailInfo/' + id);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)