在AngularJS的实际项目中,经常需要处理多个$http请求,每个$http请求返回一个promise,我们可以把多个promise放到$q.all()方法接受的一个数组实参中去。

■ 处理多个$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(){
....
})
}
})

■ $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来清除缓存

最新文章

  1. debian的版本演进
  2. Excel的数据导入到PB的DW中
  3. python列表、元祖、字典
  4. 交换机做Channel-Group
  5. [UCSD白板题] Minimum Dot Product
  6. zabbix进程构成
  7. 桥接和nat模式区别
  8. JS基础回顾,小练习(去除字符串空格)
  9. Javascript面向对象编程:构造函数的继承
  10. IOS 7 Study - Manipulating a Navigation Controller’s Array of View
  11. Eclipse中使用版本控制----Git
  12. sed 命令详解
  13. webrtc初探之一对一的连接过程(一)
  14. [HNOI 2004]L语言
  15. html-webpack-plugin不输出script标签的方法
  16. 用Python实现支持向量机并处理Iris数据集
  17. 3.docker基础架构
  18. socketserver实现FTP
  19. aspectj 表达式 execution切点函数
  20. download & excel & blob

热门文章

  1. Android:Animation
  2. centos7 部署 open-falcon 0.2.1
  3. bootgrid 刷新保持当前排序
  4. C++ code:剩余串排列
  5. MACE(2)-----模型编译
  6. cf220b
  7. pytest七:assert断言
  8. 绝对定位后,position:absolute;不能使用margin: 0 auto;实现居中;
  9. 利用反射创建User类的对象
  10. 《剑指offer》-二叉搜索树与双向链表