在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來清除緩存
