AngularJS中的$http快取以及處理多個$http請求

Darren Ji發表於2016-02-06

 

在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來清除快取

相關文章