How to Implement Caching in Angular | Caching API Response in Angular | Caching Techniques

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
I have a list of website in front of me like a Netflix NASA Trello PayPal LinkedIn Uber and do you know what is the common between all of this website this application this web application how thousands of gigabytes of data in their system and after knowing that I was curious that how they managed to load that data very quickly on a website if they manage it then what is a good time to load that so I Googled it and it seems like a from a research that somewhere around three to five seconds is a ideal time to load the website so if it is more than five seconds then it is more likely that your user will skip your website and one of it is a caching so caching is a thing where you save our data which you have taken from your server somewhere in your browser and then you use it for serving the request of your users and it helps in a faster interactivity to your users but why front end needs a caching so front-end caching is a largely underused technique but it can be a very powerful optimization technique if used in a proper way we can safely assume that a network request is a more expensive and unpredictable than retrieving your data from your local cache so whenever you are requesting any data from your server that is very expensive operation you perform HTTP requests it depends on your network how much bandwidth you have what is the capacity of your server what is your latency and all of those factors comes into a picture and that big secretly derives how fast your web application your front end is going to load this means that a caching is a really big deal and we need to implement a caching in our front-end application we are going to talk about what are the different ways where using which we can cache the backend API responses in the front-end application using angular so I'm going to show you these four methods that you can use for caching your backend API responses and in my vs code and I just created a new angular project uh using engine new and this project is very simple I have a list of users that I am fetching from a random users API and that I am just displaying on my front end I want to put a cache on this user's data that I'm getting so that my front end don't hit the random users endpoint every time instead of it it caches that response somewhere in the front end code and that we can reuse it let's see how we can Implement a caching using HTTP Interceptor in angular I have created a HTTP Interceptor folder that basically contains all the Interceptor and I will create a Interceptor file inside it which is let's call this http Interceptor dot TS along with the HTTP Interceptor we will need one more service file and the responsibility of that service file will be to check if the cache is present if cache is present then review the cache or if it's not present then now fetch the actual data so that we need so I'm going to create a one service here in my services folder so I have a cache service also so inside this cache service I am going to write a code which basically will be checking on which HTTP call you want to put a cache in my case it is a gate API call so I want to put a API cache on the get method and this service will also handle if the data is already cached then retrieve it from the browser memory if it is not cached then make a backend call to a server then pick a data and next time use the same data instead of making a request to it so this cache service is going to handle that logic so let's first import the injectable because this is the service and let's put The annotation injectable so that it becomes available to other components in this module uh in the cache service I will make one cache offset which will be a map which will hold a key value pair and inside this cash offset I am going to store my actual cache data so I have a Constructor just empty and I have a couple of methods like put get and clear so input method I will put a new cache for this URL and in the get method I will retrieve the cache for the respective URL which has been requested and in the clear method I will clear the cache if I want to you know clear a cache this will be basically useful in the scenarios where you want to clear a cache after certain intervals move to the HTTP Interceptor file and use this cache service there so first thing I will add the Imports that I need and make this again inject table and this is the HTTP Interceptor class so that's why I have implemented this interface which is HTTP Interceptor which comes from the angular core so I will write a Constructor and here in the I have Interceptor method and if you see a parameters to that Interceptor method is HTTP request and the HTTP Handler and it returns an HTTP event type of observable so inside this intercept which is a method that we need to implement in every Interceptor and this is a method where your control flow reaches so for example if I am hitting a gate API or the post API the very fundamental concept of an Interceptor is to block that intercepted and perform some of its custom execution or the custom whatever instruction that you have given before performing an actual API call to your server so this is where this is a method where your control will go if you make any API calls so in our case if we are hitting a get API for fetching the list of users control will reach first here and after this method then it will pass the control 2 back in or not so that means this is a correct place where we have to implement a caching so here we are checking that if a method is get then handle this request and we have created a cache shared response offsite that will basically return a cash shared data from the our cache service that we have just imported so from Cache service this is the get method where we will get a or data and this is the put if a cache response is not present the else case we will put we will return that data from a server and we'll put that in our cache so that on the next situation it will be available in the cache itself I will just import this operator from the rxjs and that's it we have a enough code which require for the Interceptor in the app module file we need to provide this HTTP intercept and the cache service in the provider's array so that it becomes available to rest of the components which belongs to the app module so I will import this cache service HTTP Interceptor I will import it from the should be common and use class is the one property that need we need to provide so that Interceptor understand that which class it needs to use we need to specify this mult equals to True also in our intercept else your Interceptor will not work what exactly it does if you want to know then you can read this description in the angular documentation I in order to show you that this caching works I will put some console logs so in Cache service I will just simply say if cache is found then cache a hit if cache is not there then a cache Miss and in the user list component I will put a set interval so what it does is in every three seconds it will make a fetch API called to this get users let's see how it behave now so let me refresh this and uh I can see that it says a cache Miss for the first time because that time it has requested for the actual endpoint because that it was not present in the cache then after going forward all the requests are cache hit because the data found there so this means that our caching is working and if I just remove this if I remove this Interceptor from our angular modules then now we can see that now for every request there is a new request that will be called so you can see that there are multiple HTTP requests are happening which is not good for your application like each time it is making a API call to your server and that is a extensive operation so this was the caching mechanism using HTTP interceptor now let's see the service level caching but here we don't use the HTTP Interceptor so we are not going to Interceptor level so I can just simply comment the intercepting part from my app module and uh we will implement the caching itself in the user service so we'll modify the get users method we will create one cache data offset again and uh in that cachet data we will check if a cache data exists if it exists then we'll simply return it if it doesn't exist then we will call it a actual HTTP request and then we'll put it in our object so that's it it is very similar to a plain caching mechanism but what we don't use any HTTP Interceptor so I can see that with my code it says that cache Miss once and then going for all the request will be cache hit third is caching with the rxjs operators now this is an interesting one and I will tell you there are some good operators like the share reply and the publish report are very handy to use in angular code that also makes your code look more neat and clean so I will demonstrate that also if you have observed that we are already using some of the rxjs operator like the tab and the off which are coming from the rxjs itself for our previous approaches but the share replay and the publish reply these are all together designed for a caching or data in order to use the share reply we need to have a observable type of offset so I have created a user's observable type and usually we put a dollar at the end of it to identify its observable type of offsets so similar logic if there is any value present in this observable then we will pick it if it is not there then now we'll perform of each operation so if value is not there then we'll make a HTTP call and we are using a 5 operator from the rxjs that basically very useful if you want to instructions after a synchronous operation has happened so in arcade if K8 is completed then we are going for the pipe so in that we have a tab and once the data is loaded we are saying that of fetch data from API and here comes the actual operator which is a share reply so we have provided one and one two arguments here the first argument represent the buffer size so one means we want to uh emit the last value window time applies to a cases where we have a multiple nested emissions from observable so if you go to rxj site you can see share reply has this many things that we can configure uh so a buffer size is the first as I was saying it holds the last emitter value so if I put 2 here instead of 1 then in that case it is going to hold two recent emission into its memory instead of share reply we can replace it with a publish replay and this also accept the same kind of argument so it also has a buffer size window time but there are few additional things that you can see like a times time timestamp provider I know this is too technical to understand but in a nutshell you can say that share reply won't stop emitting until it's completed but publish reply will stop after a last subscriber unsubscribes it so if there is a no subscriber to observable then it will automatically stop which is good at now the final one let's see how we can Implement a caching of API response using a local storage or session storage so this is very simple one and this has one additional advantage that if you know that session storage and the application storage they persist in your browser memory so that means if you are doing a refresh operation on your application though your storage will be remain there so unlike of our previous methods this will persist so even if you close a browser you can store that in the session storage it lasts until you have a tab open and the application storage basically stores that in your browser itself so if you don't clear that manually until it will last there will create a user subset and that will pick a data from the session storage so this is a syntax session storage or to get users and this usually tells you that this item can be a null it can possibly be null so to get rid of this error just put this uh non null assertion object which basically tells that this is not a null this cannot be a undefined or the null in the typescript if users doesn't take this in the session story then it is a cache Miss and will fetch a data from our server then we are using a pipe operator to perform a next action and in the tab we are getting access to actual data so there we are setting up that data into our session storage using a json.35 because session storage and application storage they are key value and the value need to be S3 cache hit will retrieve a data from the session storage and I am using off operator of the rxs which basically converts the data into an imitable observable and I can see that there's a cache hit and after three seconds I can cache a hit so now I will go to application and will clear a story so you can see that there is the data present here in the session storage I will manually clear this and see what happens now so now it has said cache Miss first time and then there is a cache hit second time and subsequent all the requests after this will be a cache here because it is present in your session storage so if you clear this then the cache is clearing you can Implement something like this clear method which we already wrote in the cache survey so in the clear method you can write a code to clear the or unsite the session storage application storage is similar in terms of syntax as with the session storage but instead of session storage you will write something like local storage here so that's a difference but remember session storage lasts until your tab is open and the local storage it is persisted in your browser until unless you manually clear it if you have any doubt or know some better ways to Cache a backend API responses in angular do let me know that in the comment section and I'll be more than happy to hear that from you thank you guys I hope you find this video useful
Info
Channel: Brogrammers
Views: 3,103
Rating: undefined out of 5
Keywords: javascript, api, caching, angular tutorial, caching in angular, how to add cache to a website, angular 16 tutorial, session storage in react js, api caching best practices, api caching strategies, angular caching techniques, angular cache http response, http interceptor angular, angular rxjs observable tutorial, rxjs sharereplay, rxjs sharereplay vs publishreplay, rxjs tutorial, rxjs share vs sharereplay, cache memory, how to cache data in angular, how to cache data in javascript
Id: Gjr79r2QW48
Channel Id: undefined
Length: 16min 26sec (986 seconds)
Published: Mon Jun 19 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.