詳解AngularJS中$http緩存以及處理多個(gè)$http請求的方法
$http 是 AngularJS 中的一個(gè)核心服務(wù),用于讀取遠(yuǎn)程服務(wù)器的數(shù)據(jù)。在AngularJS的實(shí)際項(xiàng)目中,經(jīng)常需要處理多個(gè)$http請求,每個(gè)$http請求返回一個(gè)promise,我們可以把多個(gè)promise放到$q.all()方法接受的一個(gè)數(shù)組實(shí)參中去。
1.處理多個(gè)$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方法第二個(gè)形參接受一個(gè)對象,該對象的cache字段可以接受一個(gè)bool類型實(shí)現(xiàn)緩存,即{cache:true},也可以接受一個(gè)服務(wù)。
通過factory方式創(chuàng)建一個(gè)服務(wù),并把該服務(wù)注入到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");
}
})
小編總結(jié):
● 實(shí)際上,實(shí)現(xiàn)緩存機(jī)制的是$cacheFactory
● 通過{cache:myCache}把緩存機(jī)制放在當(dāng)前請求中
● $cacheFactory把請求api作為key,所以清楚緩存的時(shí)候,也是根據(jù)這個(gè)key來清除緩存
以上所述是小編給大家分享的AngularJS中$http緩存以及處理多個(gè)$http請求的方法,希望對大家有所幫助。
- Angularjs中$http以post請求通過消息體傳遞參數(shù)的實(shí)現(xiàn)方法
- AngularJS $http模塊POST請求實(shí)現(xiàn)
- AngularJS出現(xiàn)$http異步后臺無法獲取請求參數(shù)問題的解決方法
- angularJS 發(fā)起$http.post和$http.get請求的實(shí)現(xiàn)方法
- 詳解AngularJS用Interceptors來統(tǒng)一處理HTTP請求和響應(yīng)
- AngularJs導(dǎo)出數(shù)據(jù)到Excel的示例代碼
- angular2中Http請求原理與用法詳解
- angular 用攔截器統(tǒng)一處理http請求和響應(yīng)的方法
- Angular的$http的ajax的請求操作(推薦)
- AngularJS基于http請求實(shí)現(xiàn)下載php生成的excel文件功能示例
相關(guān)文章
Web開發(fā)使用Angular實(shí)現(xiàn)用戶密碼強(qiáng)度判別的方法
這篇文章主要介紹了Web開發(fā)使用Angular實(shí)現(xiàn)用戶密碼強(qiáng)度判別的方法,需要的朋友可以參考下2017-09-09
AngularJS實(shí)現(xiàn)元素顯示和隱藏的幾個(gè)案例
這篇文章主要介紹了AngularJS實(shí)現(xiàn)元素顯示和隱藏的幾個(gè)案例,需要的朋友可以參考下2015-12-12
angularjs 表單密碼驗(yàn)證自定義指令實(shí)現(xiàn)代碼
這篇文章主要介紹了angularjs 表單密碼驗(yàn)證自定義指令實(shí)現(xiàn)代碼,需要的朋友可以參考下2016-10-10

