1

I'm learning Angular, and currently I'm trying to properly load a JSON file into my code, so I can iterate over it and show all the results. I could manage to do that, but once I changed the JSON, adding three more registries, I can't see them.

And that's because my JSON is being cached, as I could see on the network part of the developer console.

I tried changing my data serving service (which uses $q for asynchronous requests along with $http), so I can configure my $http object:

app.factory('dataService', ["$http", "$q", function($http, $q) {
        return {
            getAll: getAll
        }

        function getAll() {
            var defered = $q.defer();
            var promise = defered.promise;

            $http({
                url: "data.json",
                cache: false,
                method: "GET"

            })
                .success(function(data) {
                    defered.resolve(data);
                })
                .error(function(err) {
                    defered.reject(err)
                });

            return promise;
        }
    }]);

This keeps working, but didn't stop caching my JSON. I deleted my cache and executed the app again, I got the new results but once I added more registries, it kept being cached.

So, the question is... how can I avoid my JSON files to be cached?

Zerok
  • 1,323
  • 1
  • 24
  • 56

1 Answers1

2

The best thing to do is to specify proper Cache-Control header when the data.json is returned.

However if you have little or no control over the server of can force new resource to be fetched by appending a random query string parameter AKA cache buster. In angular case this could look like:

$http({
  url: "data.json?_cache_buster=" + new Date().getTime(),
  method: "GET"
})
Community
  • 1
  • 1
miensol
  • 39,733
  • 7
  • 116
  • 112
  • Thank you! It works proper, but I guess this will cache one JSON file each time I perform a request. How can I avoid that? – Zerok Feb 04 '16 at 09:10
  • @Zerok the above in practice prevents a resource from being cached. What do you mean by "this will cache JSON file each time I perform request" ? – miensol Feb 04 '16 at 11:10