Cacheing Angular Services

3A coworker asked me the best way for him to cache the results of his angular service. Not knowing the answer, we went to the documentation and discovered `$cacheFactory`. This factory will allow you to build a `Cache` object to cache data.

However, I discovered two glaring flaws with this:

  1. Using it by itself requires you to manually check if the value is in the cache, and then use the value if it is. Otherwise, you must run the service as normal. All this checking would have to be done on a per-service basis, which violates DRY principles.
  2. There is no TTL, so the data will stay in the cache until you remove the data manually.

I solved both of these issues by making my own wrapper service around angular caches. You can find the library here. You can also install it via bower using `bower install angular-service-cache`.

The main part of the code wraps the `put`, `get`, and `remove` functions of the standard cache so I can add TTL functionality.

However, the `run` function is the meat of the solution. By using `` and passing in the function, the result will be cached. If the return value is a promise, then the result of the promise will be cached. The next time the run function is called, it will return the cached value.

The target use for this module is cases in which you don’t want/need to actually reach out to your services every time, but also want more flexibility than having to manually remove entries. I will be using this in my future projects, and have many ideas on how to improve it in the future, so stay tuned!


Check out what jobs are available at Interactive Business Systems!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s