Angular default $http cache removes after route change

209 Views Asked by At

I am using Angular's default $http cache in one of my services. When the user navigates from a view to another one (I am using ui-router), the cache invalidates and all of the items will be removed from it. I want to not invalidate the cache in the whole lifetime of my application.

EDIT: For example, this factory does not return cached result after navigating to another route and it calls the server api to get the result:

cardModule.factory("myFactory", function ($http) {
    return {
        getAll: function () {
            return $http.get("all", { cache: true })
        }
    }
});

How to prevent default cache from removing items from itself after a route change?

3

There are 3 best solutions below

0
alisabzevari On BEST ANSWER

I found the source of the problem. It was my own fault. I had a code somewhere that clears the cache after the state change. There is no problem with default angular $http cache.

1
Shashank Agrawal On

That should not be related to ui-router or $http. Here are a few things you need to confirm:

  1. Is your server (which is serving your resources) is setting the cache header or not
  2. Make sure you are not using Ctrl + F5 to refresh the page
  3. If you are using Chrome browser, make sure a setting Disable cache is unchecked
3
Onyooo On

I would leave this as a comment but I don't have enough points yet..

Could you try some form of memoisation? In other words, have a model on the scope, then, if the model is undefined, trigger the $http call? Something like:

var ctrl = this;

ctrl.product = undefined; // or null

if (ctrl.product === undefined) { // or null
  $http.get(...).then(function(resp) {
     ctrl.product = resp.data;
  };
};

This way the model gets initialized, and called just once. A possible downside would be that the if statement may make this inefficient.

I have not tested this, just throwing the idea out there. I am also very interested in this problem.