Create a Cacheable class for cache API response in Angular 9 application

Tram Ho

Hello everyone, it’s been a long time since we met again, today I will share with you a little tip to cache the API response for a period of time we configure. Many times in an application that is a response that can be difficult to update in a period of time or you do not want to call that API continuously, we can cache the client. We will combine RxJS and HttpModule in Angular to create this mechanism. I will create a Cacheable <T> class with Generic data type to be able to stop for many APIs. Use ReplaySubject of RxJS to save data. The mechanism of action of this class is extremely basic as follows:

Some points people note in the above code is that the shouldCallAPI function is a function that checks the API cache time and should call the API or not. GetData function is a function to get data from components when I call this function, it will load API cache data to bind to the component. The resetCache function should be easy to understand and it will remove the cached API data. Finally, the setCacheTimeout function is used to set the time we cache API data.

Usage in Angular’s Service here I setTimeout for Cache API Data is 1 minute means that every 1 minute it will call back to API to refresh data:

How to get Cache data in Component:

The above is a small tip for you to use RxJS in an Angular application to cache data that people can comment if you have any questions or better. Have a nice week, guys, and see you guys in the next post!

Link to the original article on my blog is down here ^^

Share the news now

Source : Viblo