How to Create a Time-Based Caching Service for Angular
Home
About
Articles
If you’re interested in building a caching service for Angular that will store the observable for a HTTP call in cache, there is an excellent article by Yury Katkov that will explain exactly how to do this using RxJS .
The solution uses the shareReplay feature to be able to ‘replay’ the observable so we don’t need to execute the same HTTP call over and over again. If we’re able to locally store the observable, retrieve it and replay it, we have enough to build a basic caching service for Angular!
We’ll first build a basic caching service for Angular and then expand on it to implement time-based caching.
Using the solution in the article, I built a basic caching service for Angular that will store an observable in cache on the first HTTP call for an API endpoint used to retrieve a to-do item. Any subsequent HTTP call will retrieve the observable from cache instead of making another call to the API.
Below is how we’re deciding to retrieve the to-do from cache, or alternatively retrieving the to-do using the API endpoint:
Here’s a component that will use this logic to implement the basic caching service:
todo-individual.component.ts:
That’s great, but what if the response from the API (a to-do item in this case) changes during the lifespan of the application? If a user doesn’t reload the application for a significant amount of time, we could potentially be serving an out-of-date response.
Below is similar to before, the difference being we’re going to first determine if the item stored in cache has expired or not:
Let’s update our component to add a few more methods to implement a time-based caching service. When we add an item to the cache, we first set an expiry time (30 minutes) and ensure we have yet to exceed the expiry time when we retrieve this item from the cache:
timestamp-observable-cache.model.ts:
This will ensure we only store an item in our Angular time-based caching service for a limited amount of time, only retrieving a fresh response from the API when the item has expired.
There are often scenarios in Angular where we need to communicate between components, specifically to send data from a child component to it’s parent component. Consider this Angular 12 app for managing a to do list: Read more
In Angular there are two different types of forms for a user to input data: reactive and template-driven. I personally prefer using reactive forms as they seem to follow the separation of concerns principle, where the core functionality is in the component and the presentation layer is stored in ... Read more
Have you ever looked for a piece of HTML in the code of an Angular app and found something similar to <ng-container *ngTemplateOutlet=”navBarTemplate”></ng-container> instead? Read more
RSS