Angular Deferred: Update logic integrated with angular cache

Step by step implementation of decorating $q service to add update logic and integrate caching

Posted by Aditya Pratap Singh on July 20, 2015

Step by step implementation of decorating $q service to add update logic and integrate caching using angular-cache

The $q service in angular provides a way to implement promises in angularjs. But the issue with the service is that at times we may need a scenario where we need to resolve the promise twice.
One example scenario would be to implement caching using angular-cache, where we would want to fetch the data first from cache and simultaneously call the api to fetch the data. In this scenario we will have to resolve the promise twice: First while returning data from cache , Second when the data has been fetched from service api. We will see the step-by-step implementation of the scenario using AugmentedDeferredService service and angular-cache.

  1. Create an angular service AugmentedDeferredService which augments the behaviour of $q service. In order to do so, we will add an update() method using a queue to track whether the promise has been resolved once.
  2. Add angular-cache to your project
  3. bower install angular-cache --save
  4. Create an angular service CacheManager to manage the Caching logic for http requests.
  5. In order to use the above in controllers, you need to chain the update() method after then method, as explained below
With the above steps, the workflow to implement caching embedded along side http requests is very inherent.