Ajay K
Ajay K

Reputation: 85

AngularJS cache issue in webpage

I have a Spring AngularJS web application where I get JSON data using from the Spring controller and I use this data with $http method in the angular factory and write the necessary angular controller for the same. I use html files in order to display this data. I am fetching form field names and field types dynamically in the html pages. My problem is I am getting what appears to be cache issue when I initially login and go to the respective page. The parameters are showing up as they are from the html page. It is only after I refresh the page I am getting the proper data. Could anyone help me out in figuring out what is going on?

Upvotes: 1

Views: 267

Answers (2)

icfantv
icfantv

Reputation: 4643

While Lee's answer is correct and how jQuery used to do it (I don't know if it still does) ages ago with AJAX requests. But it's hacky.

The right way to do this is to properly set your Cache-Control, Pragma, and Expires headers on your server responses. Since you're using Spring on the server, am I correct in assuming you're using some sort of JSP Servlet container (like Apache Tomcat)?

If so, Tomcat has built-in functionality for you to do this via your web.xml file. Take a look at the org.apache.catalina.filters.ExpiresFilter class. Here's a small sample:

  <filter>
    <filter-name>ExpiresFilter</filter-name>
    <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
    <init-param>
      <param-name>ExpiresExcludedResponseStatusCodes</param-name>
      <param-value>302, 304, 404, 500, 503</param-value>
    </init-param>
    <init-param>
      <param-name>ExpiresByType text/html</param-name>
      <param-value>access plus 1 day</param-value>
    </init-param>
    <init-param>
      <param-name>ExpiresByType application/javascript</param-name>
      <param-value>access plus 1 day</param-value>
    </init-param>
    <init-param>
      <param-name>ExpiresByType image</param-name>
      <param-value>access plus 1 month</param-value>
    </init-param>
  </filter>

Since application/json is omitted, any JSON requests or responses are NOT cached. This setup works nicely in our web application.

One thing I will note is that with these headers set, simply refreshing your browser page will not work - it will still fetch from the local cache. That said, Chrome has an option to disable the cache while the debug console is open, so this issue is easily mitigated.

Upvotes: 0

lee
lee

Reputation: 111

you can add timestamp to JSON URL

var JSONURL = "your json url here";
var t = getTime();

$http({
  method: 'GET',
  url: JSONURL + "?t=" + t
  }).success(function () {
});

Upvotes: 1

Related Questions