0

I have this snippet below in my controller:

var cache = $cacheFactory('contacts');

var data = cache.get('contacts');

if(!data) {
    Contacts.get()
        .success(function(result) {
            data = result;
            cache.put('contacts', data);
        });
}

My Contacts.get() call returns 152KB of data and is taking ~1.5s to run. I'm trying to cache this data since it does not need to be up to date.

However, every time I refresh the HTTP call is still being made and i'm seeing undefined in the console from logging cache.get('contacts') and data.

How can I cache this data returned from the HTTP call and reference it in the scope?

1 Answer 1

2

How does your data looks like ? In case it's a json object, just try to stringify it before caching it, something like

cache.put('contacts', JSON.stringify(data));

---- UPDATE ----

You can't use $cacheFactory to persist data. $cacheFactory does not persist over sessions and should only used for in-session persistency, what you're looking for is localStorage. there are a lot of good libraries for easily integrating localStorage with angular (for instance https://github.com/grevory/angular-local-storage)

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

4 Comments

Are you trying to use it in the same session or you try refresh the browser ? $cacheFactory only caches the data for the current session. Have you considered using localStorage instead ? there are great libs for that
Yes I'm sure, $cacheFactory uses in-memory cache and it should only used for in-session persistency. localStorage should be used for what you want.
I didn't understand, why should I delete my answer ?
someone else might have gotten it wrong as well, I think I helped you after all didn't I ?

Your Answer

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