当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > 详解AngularJS中$http缓存以及处理多个$http请求的方法

详解AngularJS中$http缓存以及处理多个$http请求的方法

2018年06月17日  | 移动技术网IT编程  | 我要评论

$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请求的方法,希望对大家有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网