John
John

Reputation: 136

Angular 8 Http get request with no cache

A get request in my angular application is able to fetch the data but that request is being stored in cache and whenever i trigger other page and return back to that page i see nothing the get request is getting triggered but this is what the response in network tab

Request URL: example.com
Request Method: GET
Status Code: 301  (from disk cache)
Remote Address: 104.27.136.237:443
Referrer Policy: no-referrer-when-downgrade

this is what i'm getting i just want to trigger the http get or force that call and fetch objects and display them

here is my code part

constructor(private http:HttpClient,public dialog: MatDialog){
    const httpOptions = {
      headers: new HttpHeaders({
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Content-Type':  'application/json',
        'API-KEY': localStorage.getItem("key"),

      })
    }
    this.back =this.backend + localStorage.company_domain
    this.backenddata=this.http.get(this.back,httpOptions).subscribe(
      backenddata=>{
    let ok=backenddata["results"];
    console.log(ok);
}}

k

Note:By refreshing i'm able to fetch the data but while changing from one page to another page using angular route i'm seeing that 301 response in the network tab
Note:I Have already tried HttpInterceptors still had no luck with that 
Note:  Tried <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />  
  <meta http-equiv="Pragma" content="no-cache" />  

is there any better option to trigger requests without getting interfered by cache

Upvotes: 3

Views: 6711

Answers (1)

cjd82187
cjd82187

Reputation: 3593

From the client side, if you change the URL every time you make the get request by appending a new query param, the browser won't cache it. We can add a cache bust query param with a value of the current time in miliseconds.

This is not very elegant, but it could help.

constructor(private http:HttpClient,public dialog: MatDialog){
    const httpOptions = {
      headers: new HttpHeaders({
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Content-Type':  'application/json',
        'API-KEY': localStorage.getItem("key"),

      })
    }
    // the new Date().getTime() will add the current time in miliseconds to the end
    this.back = `${this.backend}${localStorage.company_domain}?cache_bust=${new Date().getTime()}`
    this.backenddata=this.http.get(this.back,httpOptions).subscribe(
      backenddata=>{
    let ok=backenddata["results"];
    console.log(ok);
}}

The better way would be to solve it on the client side by setting proper cache control headers. How to do that depends on your server technology.

Upvotes: 3

Related Questions