Skip to content Skip to sidebar Skip to footer

Caching With Angularjs

Currently I'm trying to cache a user's information. I give you guys a scenario of what is happening. a user is trying to log in with an account A. Account A's name appears on the

Solution 1:

There are two different caches that may be involved in your app. First it's the angular cache which you have set below {cache: true}

authFactory.getUser = function() {
    if (AuthToken.getToken())
        return$http.get('/api/me', {cache: true});
    elsereturn$q.reject({ message: 'User has no token.' });        
};

This cache is only there for the duration of the app, once you leave or reload the page, it's gone!

The other cache which is the browser cache is a little more complex to deal with. Note this has no relationship with the Angular cache, so if this is your problem simply turning off {cache: false} wont help. To prevent cache you will need to send a list of different caching headers in your restful API and it may not always work.

The easiest way to prevent cache is to add a version to your url which doesnt actually affect your results but tricks your browser into thinking that it's a different url. This is referred to as Cache Busting.

The easiest way to cache bust is to add a Math.Random() to append to the url. The chances of Math.Random to be the same is probably in the billions.

authFactory.getUser = function() {
    if (AuthToken.getToken())
        return$http.get('/api/me?rand=' + Math.random(), {cache: true});
    elsereturn$q.reject({ message: 'User has no token.' });        
};

However, if you want a better way to do it specific for your app, you could append the username to your url. This way it will cache for the same users which means you are actually taking advantage of the caching mechanism and not getting tied down by it!

authFactory.getUser = function() {
    if (AuthToken.getToken())
        return$http.get('/api/me?user=' + <username>, {cache: true});
    elsereturn$q.reject({ message: 'User has no token.' });        
};

Post a Comment for "Caching With Angularjs"