Angular : how to prevent cache

Viewed 521

Every time that I release a new version of my app, during a few hours/day I have some users reporting that they do not see the changes until they reload website with ctrl+F5.

I've setup some confs to force browsers not to use cache :

In index.html :

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

In angular.json

...
"configurations": {
  "production": {
    "outputHashing": "all",
...

But when i navigate on deployed app, and I check in the Chrome's network tab, I can see that for main.js (which do contains a hash in it's name) :

Status Code: 200 OK (from disk cache)

How can I totaly prevent browser to use cache?

Edit :

What I see is that if I navigate on the website typing the address in the address bar, or using a favorite, an old version of the files are loaded. But if I go for F5 (even without ctrl) I get the current version.

Even worse : I use F5 -> get new version. Then I use fav/type the address -> back to the older version... I'm confused

Also it seems that I get the older version of the website only when I navigate on the website base url. If URL is an internal page, I get current version.

Many thx

1 Answers

I had the same problem. finally I resolve it by implementing an auto reload mechanism by a method in app.component.ts like this:

insertParam(key, value) {
  key = encodeURIComponent(key);
  value = encodeURIComponent(value);

  // kvp looks like ['key1=value1', 'key2=value2', ...]
  let kvp = document.location.search.substr(1).split('&');
  let i=0;

  for(; i<kvp.length; i++){
      if (kvp[i].startsWith(key + '=')) {
          let pair = kvp[i].split('=');
          pair[1] = value;
          kvp[i] = pair.join('=');
          break;
      }
  }

  if(i >= kvp.length){
      kvp[kvp.length] = [key,value].join('=');
  }

  // can return this or...
  let params = kvp.join('&');

  // reload page with new params
  document.location.search = params;
}



CheckVersion(){

  this.versionService.getVersion().subscribe(
    (x)=>{
      console.log(x);
      console.log(environment.version);
      if(x.value!=environment.version){
        console.log('reload');
        console.log(this.getParameterByName('version'));
        console.log(x.value);
        if(this.getParameterByName('version')!=x.value){
        this.insertParam('version',x.value);
        }
      }
    },
    (e)=>{
    console.log(e);
    }
        );
}

In the server side implement a API function to return the last version

Related