ngCachedResource
An AngularJS module to interact with RESTful server-side data sources, even when the browser is offline. Uses HTML5 localStorage under the hood. Closely mimics the behavior of the core ngResource module.
A simple example
var Article = ; // GET requests:var firstArticle = Article;firstArticle$promise;firstArticle$httpPromise; // POST/PUT/DELETE requests: // If this fails initially, possibly because of a bad connection, we will// try sending it againArticle;
Usage
Provides a factory called $cachedResource
that returns a "CachedResource" object.
;
Arguments
-
cacheKey,
String
An arbitrary key that will uniquely represent this resource in localStorage. When the resource is instanciated, it will check localStorage for any -
url,
String
Exactly matches the API for theurl
param of the $resource factory. -
paramDefaults,
Object
, (optional)
Exactly matches the API for theparamDefaults
param of the $resource factory. -
actions,
Object
, optional
Exactly matches the API for theactions
param of the $resource factory.
Returns
A CachedResource "class" object. This object is basically a swap-in replacement for an
object created by the $resource
factory with the following modified or additional
properties:
-
Resource.$promise
: For GET requests, if anything was already in the cache, this promise is immediately resolved (still asynchronously!) even as the HTTP request continues. -
Resource.$httpPromise
: For all requests, this promise is resolved as soon as the corresponding HTTP request responds.
Details
Asking for a cached resource with get
or query
will do the following:
-
If the request has not been made previously, it will immediately return a
resource
object, just like usual. The request will go through to the server, and when the server responds, the resource will be saved in a localStorage cache. -
If the request has already been made, it will immediately return a
resource
object that is pre-populated from the cache. The request will still attempt to go through to the server, and if the server responds, the cache entry will be updated.
Updating a CachedResource object will do the following:
- Add the resource update action to a queue.
- Immediately attempt to flush the queue by sending all the network requests in the queue.
- If a queued network request succeeds, remove it from the queue and resolve the promises on the associated resources (only if the queue entry was made after the page was loaded)
- If the queue contains requests, attempt to flush it once per minute OR whenever the browser sends a navigator.onOnline event.