Cache get requests by implementing HttpInterceptor in Angular
Sometime there is a need to cache the GET requests so that browser doesn’t have to hit server to fetch same data when same service is invoked serially or in parallel. We will implement HttpInterceptor interface of Angular to solve the purpose.
Step 1: Create a service to add URIs for caching
First of all we will create a service that will be used to register the URIs to be cached when we implement the HttpInterceptor.
Step 2: Add CacheRegistrationService to main module providers
Next step is to make this service available via providers of the application module
Step 3: Implementing HttpInterceptor
Now, let’s create our class to cache the URIs.
This will cache only GET requests whose URIs has already been registered for caching via CacheRegistrationService. It will return last cached request (in progress) in case of parallel requests for same URI and will return last cached response in case of serial request for the URI that has already been responded by server. This will also entertain the header “reset-cache” in case the request initiator wants to clear previous cache for any URI and make a fresh request to server for updated data.
Step 4: Adding interceptor to main module providers
Step 5: Register any service for caching and try clearing its cache after some time
Let’s create a new service which will fetch user data from server. This service will import CacheRegistrationService and add a URI for caching. When function fetchUserData will be called for first time, a new request will hit server to get the latest user’s data. All subsequent requests will serve the cached data. Later if developer wants to fetch fresh data for the user then one needs to call fetchUserData with a true parameter so that function can add a header “reset-cache” to the request and our interceptor knows that it has to reset the cache for that URI as soon as header is set as “reset-cache”.
I hope this article was helpful.
~ Vikesh M