angularJs中缓存数据,免去重复发起请求的几种写法
2016-12-26 18:09
351 查看
带缓存处理的两种写法
过程:点击button触发load()方法,请求数据成后显示到页面中。如果已经请求过则从缓存中读取。
在线浏览
写法1:
写法2:
感觉第二种写法好些,注意细节。
写法3 利用闭包缓存结果
过程:点击button触发load()方法,请求数据成后显示到页面中。如果已经请求过则从缓存中读取。
在线浏览
写法1:
function demo(){ if (demo.cache == undefined) { return $http.get('https://api.github.com/users/github') .then(function(data, status, headers){ demo.cache = data.data; return $q(function (resolve, reject) { resolve(demo.cache); }); }) }else { console.log('from cache'); return $q(function (resolve, reject) { resolve(demo.cache); }); } } // 点击加载 $scope.load = function() { demo().then(function(data){ $scope.list = data.data; }) }
写法2:
感觉第二种写法好些,注意细节。
function demo(){ let deferred = $q.defer(), that = this;if (that.cache == undefined) { $http.get('https://api.github.com/users/github') .success(function(data, status, headers){ that.cache = data; deferred.resolve(that.cache); }) }else { console.log('from cache'); deferred.resolve(that.cache); } return deferred.promise; } // 点击加载 $scope.load = function() { demo().then(function(data){ $scope.list = data; }) }
写法3 利用闭包缓存结果
// 利用闭包缓存结果 function demo2() { let defer = $q.defer(), cache; return function() { if (cache == undefined) { $http.get('https://api.github.com/users/github') .then((res) => { cache = res.data; defer.resolve(cache); }) }else { console.log('from cache'); defer.resolve(cache); } return defer.promise; } } // 点击加载 let startDemo = demo2(); $scope.load = function() { startDemo().then(function(data){ $scope.list = data; }) }
相关文章推荐
- 分享SQL语句从M条数据读取到N条的几种写法!
- 教你几种在SQLServer中删除重复数据方法
- jquery 请求ie缓存,数据不更新的问题【ajax禁用缓存解决ie数据不更新的问题】
- .net中防止刷新页面重复提交数据的几种方法
- 数据列表过滤重复值几种方法的性能比较
- 技巧:删除表中重复数据的几种方法
- .net 防止页面刷新重复提交(表单提交后保留上一次数据缓存,刷新提交)
- 找出最近不重复数据的sql写法
- 关于js处理ajax请求返回json数据时出现页面缓存的解决方案(适用于showdialog)
- 教你几种在SQLServer中删除重复数据方法
- 查找不重复的统计数据的sql语句的写法
- 几种判断2表重复数据的相关语句
- jquery 请求ie缓存,数据不更新的问题【ajax禁用缓存解决ie数据不更新的问题】
- SQL Server中删除表中重复数据的几种方法
- 整理最近新学到的几种sql写法(一)动态“循环”更新表内数据
- Sql Server 中常见的几种删除重复数据的方法
- asp.net清除页面缓存,防止页面回退重复提交数据及防止同一用户同时登录
- jquery之利用ajax与服务器交谈(发起GET和POST请求之获取JSON数据)
- 几种在SQLServer中删除重复数据方法
- jQuery发送ajax请求,IE有缓存,数据不更新问题