Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Prevent Caching in IE8 when using AngularJS Models

My technology stack is -

  1. AngularJS
  2. Bootstrap
  3. Spring MVC
  4. Hibernate

What am I doing :

There is a list of Items on which I am doing CRUD (Create, Read, Update and Delete)

  1. Posting form Data via Angular Controller to a Spring Controller.
  2. Spring Controller -> DAO method -> DB is updated
  3. Spring Controller Returns "Y" or "N"
  4. Angular gets the Status Message and Reloads the Angular Model(A Json Array to populate the List of Items)
  5. Same with Update and Delete

My objective is to achieve real-time data manipulation without page reload.

This works fine in Chrome. However, IE can not detect the Model Change. It keeps displaying the data prior to addition/updation/deletion (from its cache). Only after I clear the cache manually, am I actually able to see the changed Model.

Need help on how to resolve this problem with IE8 and above.

P.S. I have already tried setting the meta headers

like image 527
Avinash Avatar asked Mar 05 '26 02:03

Avinash


2 Answers

You can set

"No-Cache headers to the response on server side"

var AppInfrastructure = angular.module('App.Infrastructure', []);

and in Angularjs you can write interceptor below is the sample code:

AppInfrastructure
    .config(function ($httpProvider) {
        $httpProvider.requestInterceptors.push('httpRequestInterceptorCacheBuster');
    })    
    .factory('httpRequestInterceptorCacheBuster', function () {
        return function (promise) {
            return promise.then(function (request) {
                if (request.method === 'GET') {
                    var sep = request.url.indexOf('?') === -1 ? '?' : '&';
                    request.url = request.url + sep + 'cacheSlayer=' + new Date().getTime();
                }

                return request;
            });
        };
    });   
like image 85
JQuery Guru Avatar answered Mar 06 '26 19:03

JQuery Guru


same as what Jquery Guru mentioned above, but it is config in newer version of angular

.factory('noCacheInterceptor', function () {
        return {
            request: function (config) {
                console.log(config.method);
                console.log(config.url);
                if(config.method=='GET'){
                    var separator = config.url.indexOf('?') === -1 ? '?' : '&';
                    config.url = config.url+separator+'noCache=' + new Date().getTime();
                }
                console.log(config.method);
                console.log(config.url);
                return config;
           }
       };
});

you should remove console.logs after verifying

like image 30
dillip pattnaik Avatar answered Mar 06 '26 18:03

dillip pattnaik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!