0

I have the next problem

I'm trying to caching a get request with $http but seems not working, the cache variable always get undefined

Sample code:

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 Answer 1

1

The problem was with the URL which you are passing to get the cache.

This works.

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 will store the cache data with full URL including params so your key should have the params.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.