How to deal with HTTP Request cashing in Angular with HttpClient

I have observed a very strange behavior of an Angular application in IE. Although I was refreshing page again and again to fetch the latest data from backend API, it always loads old data. The backend application is in Asp.net Core 2.2. I thought there is an issue with the asp.net application. I put a debugger to investigate the issue in detail it is not even hitting the debugger.

Thanks to browser developer tools, I have observed that I am getting the cached result. I have solved this issue by appending headers to the HTTP request for preventing the cached result. The Cache-Control header which prevents all caching. What you need to do add an extra header into the HTTP request.

Adding header in each and every call is difficult. So we need to find the generic solution to this problem. I am already using AuthInterceptor for adding Authorization token in the header. So I used that file for adding this new header.

Create an HTTP interceptor:

There are three steps involved in it.

  • Create a class that implements an HttpInterceptor interface.
  • Add the required functionality in the intercept method.
No alt text provided for this image

In the second last line, I have added the Cache-Control header.

  • Add the interceptor to your AppModule.ts file
No alt text provided for this image

After doing this you will be getting accurate data from API. If still there is a need for caching data try to do that on the server-side.

Cheers ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了