緩存AngularJS JSONP請求

最近在用angularjs寫了一個github page博客,要用的github的jsonp api來獲取文件列表。

這是github的api: GET /repos/:owner/:repo/contents/:path

我想要在AngularJS緩存下JSONP請求。一開始代碼是這樣寫的:
$http.jsonp("https://api.github.com/repos/cs1707/blog/posts?callback=ANGULAR_CALLBACK",{ cache : true}); 但是奇怪的是{ cache : true } 并沒有起作用。在chrome查看網絡請求,發現有這樣幾個請求

https://api.github.com/repos/cs1707/blog/contents/posts?callback=angular.callbacks._0
https://api.github.com/repos/cs1707/blog/contents/posts?callback=angular.callbacks._1
https://api.github.com/repos/cs1707/blog/contents/posts?callback=angular.callbacks._2

說明AngularJS對于JSONP請求每次都生成不同的url。

下面用$cacheFactory緩存JSONP請求。

app.service("GBlog", ["$q", "$http", "$cacheFactory", function($q, $http, $cacheFactory) {
        var cacheEngine = $cacheFactory("list"); // caches name
        this.getList = function(url){
            var cache = cacheEngine.get("list");
            var d = $q.defer();
            if(cache) {
                // get from cache
                d.resolve(cache);
            } else {
                $http.jsonp(url,{cache: true})
                    .success(function(data){
                        // store to cache
                        cacheEngine.put("list", data);
                        d.resolve(data);
                    })
                    .error(function(error){
                        d.reject(error);
                    });
            }
            return d.promise;
        }

在chrome查看網絡請求。可以看到只生成這樣一個請求https://api.github.com/repos/cs1707/blog/contents/posts?callback=angular.callbacks._0 OK 緩存JSONP請求成功。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容