2

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?

alisabzevari
  • 8,008
  • 6
  • 43
  • 67

3 Answers3

2

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.

alisabzevari
  • 8,008
  • 6
  • 43
  • 67
1

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.

Onyooo
  • 105
  • 1
  • 10
  • Yes, I can. But angular has a nice caching mechanism out of the box and I want to use its best practices. Also I can write my own cacheProvider but I think default caching feature of angular can solve the problem. – alisabzevari Apr 16 '16 at 10:18
  • Awesome! You're way more advanced than I am ^^ I'll do some more research and keep an eye on this question. – Onyooo Apr 16 '16 at 10:33
  • the [NG-Book](https://www.ng-book.com/p/Caching/#default-http-cache) suggests manipulating the default $cache with something like: `var cache = $cacheFactory.get('$http'); var usersCache = cache.get('http://example.com/api/users.json');`. That may be shorter than writing a custom one. – Onyooo Apr 16 '16 at 10:52
0

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
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • I don't refresh the page, I just navigate to another view. The problem is not related to the http protocol cache. It is the problem of angular's $http cache. – alisabzevari Apr 16 '16 at 09:02