0

我有下一个问题

我正在尝试使用 $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
    };
}
4

1 回答 1

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 将使用包含参数的完整 URL 存储缓存数据,因此您的密钥应该具有参数。

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

于 2016-04-14T04:01:35.037 回答