亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解AngularJS中$http緩存以及處理多個$http請求的方法

 更新時間:2016年02月06日 15:12:34   作者:Darren Ji  
$http 是 AngularJS 中的一個核心服務,用于讀取遠程服務器的數(shù)據(jù),通過本文給大家介紹AngularJS中$http緩存以及處理多個$http請求的方法,希望的朋友一起學習吧

$http 是 AngularJS 中的一個核心服務,用于讀取遠程服務器的數(shù)據(jù)。在AngularJS的實際項目中,經(jīng)常需要處理多個$http請求,每個$http請求返回一個promise,我們可以把多個promise放到$q.all()方法接受的一個數(shù)組實參中去。

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類型實現(xiàn)緩存,即{cache:true},也可以接受一個服務。

通過factory方式創(chuàng)建一個服務,并把該服務注入到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");
}
})

小編總結:

● 實際上,實現(xiàn)緩存機制的是$cacheFactory
● 通過{cache:myCache}把緩存機制放在當前請求中
● $cacheFactory把請求api作為key,所以清楚緩存的時候,也是根據(jù)這個key來清除緩存

以上所述是小編給大家分享的AngularJS中$http緩存以及處理多個$http請求的方法,希望對大家有所幫助。

相關文章

最新評論