AngularJS如何使用$ http和$ cacheFactory缓存请求

时间:2016-04-13 17:33:48

标签: angularjs caching cachefactory

我有下一个问题

我正在尝试使用$ http缓存get请求,但似乎无效,缓存变量总是未定义

示例代码:

myApp.factory("sample", ["$http", "$q", "$cacheFactory", sample]);

function sample($http, $q, $cacheFactory) {
    function getData() {
        var url = "http://whatever ...";

        return $http.get(url, {
            params: {
                Id: 10
            },
            cache: true
        })
        .then(function(response) {
            // trying to get the cached data
            var cache = $cacheFactory.get("$http");
            var data = cache.get(url); // undefined -> ??

            return response.data;
        })
        .catch(function(error) {
            return $q.reject(error);
        });
    }

    return {
        getData: getData
    };
}

1 个答案:

答案 0 :(得分:1)

问题在于您传递的URL以获取缓存。

这很有效。

myApp.factory("sample", ["$http", "$q", "$cacheFactory", sample]);

function sample($http, $q, $cacheFactory) {
    function getData() {
        var url = "http://whatever ...";

        return $http.get(url, {
            params: {
                Id: 10
            },
            cache: true
        })
        .then(function(response) {
            // trying to get the cached data
            var cache = $cacheFactory.get("$http");
            var data = cache.get(url+"?id=10"); // cacheFactory will store the cache data with full URL including params so your key should have the params
            return response.data;
        })
        .catch(function(error) {
            return $q.reject(error);
        });
    }

    return {
        getData: getData
    };
}

cacheFactory将使用包含params的完整URL存储缓存数据,因此您的密钥应该包含params。

cache.get(url+"?id=10");