详解AngularJS中$http缓存以及处理多个$http请求的方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了详解AngularJS中$http缓存以及处理多个$http请求的方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2029字,纯文字阅读大概需要3分钟。
内容图文
$http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。在AngularJS的实际项目中,经常需要处理多个$http请求,每个$http请求返回一个promise,我们可以把多个promise放到$q.all()方法接受的一个数组实参中去。
1.处理多个$http请求
angular.module('app',[]) .controller('AppCtrl', function AppCtrl(myService){ var app = this; myService.getAll().then(function(info){ app.myInfo = info; }) }) .service('myService', function MyService($http, $q){ var myService = this; user = 'https://api...', repos = '', events = ''; myService.getData = function getData(){ return $http.get(user).then(function(userData){ return { name:userData.data.name, url:userData.data.url, repoCount: userData.data.count } }) }; myService.getUserRepos = function getUserRepos(){ return $http.get(repos).then(function(response){ return _.map(response.data, function(item){ return { name: item.name, description:item.description, starts: item.startCount } }) }) } myService.getUserEvents = function getUserEvents(){ ... } myService.getAll = function(){ var userPromise = myService.getData(), userEventsPromise = myService.getUserRepos(), userReposPromise = myService.getUserRepos(); return $q.all([userPromise, userEventsPromise, userReposPromise]).then(function(){ .... }) } })
2.$http请求缓存
$http的get方法第二个形参接受一个对象,该对象的cache字段可以接受一个bool类型实现缓存,即{cache:true},也可以接受一个服务。
通过factory方式创建一个服务,并把该服务注入到controller中去。
angular.module('app',[]) .factory("myCache", function($cacheFactory){ return $cacheFactory("me"); }) .controller("AppCtrl", function($http, myCache){ var app = this; app.load = function(){ $http.get("apiurl",{cache:myCache}) .success(function(data){ app.data = data; }) } app.clearCache = function(){ myCache.remove("apiurl"); } })
小编总结:
● 实际上,实现缓存机制的是$cacheFactory
● 通过{cache:myCache}把缓存机制放在当前请求中
● $cacheFactory把请求api作为key,所以清楚缓存的时候,也是根据这个key来清除缓存
以上所述是小编给大家分享的AngularJS中$http缓存以及处理多个$http请求的方法,希望对大家有所帮助。
内容总结
以上是互联网集市为您收集整理的详解AngularJS中$http缓存以及处理多个$http请求的方法全部内容,希望文章能够帮你解决详解AngularJS中$http缓存以及处理多个$http请求的方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。