1

My previous question highlighted caching possibilities in my services.

The documentation for ngResource (v1.3.0-build.2417 (snapshot) at the time of writing this) shows a cache flag.

However, the cache will only be populated after the first call to service.get(id). I want to be able to pre-populate the resource cache with an item that was retrieved from elsewhere

(It's perfectly reasonable to have the same item be available from 2+ endpoints. E.g. you can have a task available at /task/5 and as part of a collection at /projects/99/tasks if task 5 is part of project 99)

I've tried this, but it is very ugly:

// return the API in the project service
return {
        project: null, // my own hand-rolled cache

        get: function (id) {

            // check cache
            if (this.project != null && this.project.id == id) {
                console.log("Returning CACHED project", this.project);
                var future = $q.defer();
                future.resolve(this.project);
                // UGLY: for consistent access in the controller
                future.$promise = future.promise;
                return future;
            } else {
                return Projects.get({
                    id: id
                });
            }
        }, // etc

And in the controller:

$q.when(projectService.get($routeParams.id).$promise).then(function(project) {
  // etc 

How do I pre-populate the cache using AngularJS idioms?

1 Answer 1

0

You can put the cache value manually into the cache factory. Inject $cacheFactory, get the http cache, and put the object into the cache with the key being the path of the resource.

For example:

var task = { 
    // ... task object here ... 
};

var httpCache = $cacheFactory.get('$http');
httpCache.put('/projects/99/tasks/5', task);
httpCache.put('/task/5', task);

One thing to note, if you set the cache flag in your resource to true, it'll default to use the $http cache. You can also set it to a custom cacheFactory instance. In that case, you'd just put the value to your custom cache instead.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.