Search code examples
angularpdfangular6browser-cachecache-control

How to prevent or avoid Cache in Angular 2 + Applications?


I have a situation where i send parameters to an API which in turn generates dynamic pdf & API sends me the path of newly generated file. When i open the file in browser it shows newly generated file, but In my DOM I still see the old file untill & unless i close the browser & hit the API Again. I am previewing the generated pdf file as follows :

TS PART :

this.http.postMethod("report/auditAdmin", data).subscribe((res: any) => {
        this.toolbar = "#toolbar=0&navpanes=0";
        this.pdfSrc = res.filepath + this.toolbar;
        this.Url = this.sanitizer.bypassSecurityTrustResourceUrl(this.pdfSrc);
      });

HTML PART :

<object [data]="Url" type="application/pdf" width="100%" height="1000px"></object>

Solution

  • The issue is not with the API Cache or Angular, The issue is with the object control. When we try to load the data like pdf file or any other external content object sends a get request to show the content (get request can be viewd in browser's network tab).

    So the simple solution is append querystring to your pdf path.

    this.http.postMethod("report/auditAdmin", data).subscribe((res: any) => {
                this.toolbar = "#toolbar=0&navpanes=0";
                let ramdom = Math.random();
                this.pdfSrc = res.filepath + "?v=" + random + this.toolbar;
                this.Url = this.sanitizer.bypassSecurityTrustResourceUrl(this.pdfSrc);
              });
    

    Now whenever your object tries make a get request to pdf file each request will be fresh because of querystring and hence data will not get loaded from cache.