Angular Caching issue in IE for $http

In this blog post I wanted to share one problem that I faced while working on Angular 4 project. I was using Angular 4 as a client side framework and ASP.NET Core Web API for server side operations. The problem I faced was related to HTTP GET request, which was caching the request for approx. 1 minute during back and forth page navigation and skipping calling my Web API. I put browser console logging to know what is happening but the http.get() operation was not hitting my Web API. The strange thing that this was only happening with IE and other browsers which I tried like Chrome, Mozilla were working fine. As the data was real time, I don’t wanted HTTP operation to be cached and wanted to invoke my API on every navigation.

To resolve this error, I had to set few headers which resolved the caching problem and here is the code snippet showing how you can set headers like Cache-control, Expires and Pragma and pass it in the HTTP request.

export class DataComponent implements OnInit {
private httpObj: Http;    private headersAdditional: Headers;
constructor(http: Http) {
this.httpObj = http;

this.headersAdditional = new Headers();
this.headersAdditional.append(‘Cache-control’, ‘no-cache’);
this.headersAdditional.append(‘Cache-control’, ‘no-store’);
this.headersAdditional.append(‘Expires’, ‘0’);
this.headersAdditional.append(‘Pragma’, ‘no-cache’);
}

public ngOnInit(): any { this.LoadTables(); }

private LoadTables() {
      this.httpObj.get(‘/api/Data/GetData’, {headers: this.headersAdditional }).subscribe(
      result => { //do something with the response });
}

Hope this helps!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s