How to disable caching with HttpClient get in Angular 6

后端 未结 4 1176
感动是毒
感动是毒 2020-12-09 16:52

I\'m writing an Angular SPA app, that uses HttpClient to get values from my backend.

What is the easy way to tell it not to cache? The first time I ask it gets the v

4条回答
  •  没有蜡笔的小新
    2020-12-09 17:18

    As answered by Pramod, you can use http request interceptor to modify or set a new header on the request. Below is a much simpler way of setting headers on http request interceptor for Later angular versions(Angular 4+). This approach would only set or update a certain request header. This is to avoid removing or overriding some important headers like the authorization header.

    // cache-interceptor.service.ts
    import { Injectable } from '@angular/core';
    import {
      HttpInterceptor,
      HttpRequest,
      HttpHandler,
    } from '@angular/common/http';
    
    @Injectable()
    export class CacheInterceptor implements HttpInterceptor {
    
      intercept(req: HttpRequest, next: HttpHandler) {
        const httpRequest = req.clone({
          headers: req.headers
            .set('Cache-Control', 'no-cache')
            .set('Pragma', 'no-cache')
            .set('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT')
        })
    
        return next.handle(httpRequest)
      }
    }
    
    // app.module.ts
    
      import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'
      import { CacheInterceptor } from './cache-interceptor.service';
    
      // on providers
      providers: [{ provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true }]
    

提交回复
热议问题