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 に答える