Table of Content

Angular is a great choice for any large scale enterprise projects because it is opinionated and brings the whole team together on many things. It is like having a headstart for your development team. Though angular has so many things defined, still there are some things that you have to figure out on your own.

One such thing is caching HTTP requests, as per the famous quote by Phil Karlton,

“There are only two hard things in Computer Science: cache invalidation and naming things.”, Caching things is very easy but clearing the cache is difficult. We are going to see an approach that puts you in control of both caching an HTTP request and invalidating the cache.

First, let’s define a property in your service which caches the result of the HTTP request

data-sheets-value=“{“1”:2,“2”:“private userList$: Observable;”}” data-sheets-userformat=“{“2”:513,“3”:{“1”:0},“12”:0}”>private userList$: Observable;

I’m using any type here for the sake of example, in real-world applications you should not be using any type like this. Now let us write the service method that makes the HTTP request.

public getUsers$(): Observable {

if (!this.userList$) {

this.userList$ = this.httpClient.get(‘/users’);

}

return this.userList$;

}

The above code is pretty self-explanatory, we are checking if the observable is already defined and if it isn’t we are making the HTTP call and then store the reference in the member observable we created. Next time this function gets called, the existing reference to the observable will be returned without actually making a fresh HTTP call.

#angular #http #development #coding

How to Cache HTTP Requests In Angular
1.30 GEEK