最近在用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查看網(wǎng)絡請求,發(fā)現(xiàn)有這樣幾個請求
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查看網(wǎng)絡請求。可以看到只生成這樣一個請求https://api.github.com/repos/cs1707/blog/contents/posts?callback=angular.callbacks._0
OK 緩存JSONP請求成功。