Prevent IE11 caching GET call in Angular 2

前端 未结 7 564
甜味超标
甜味超标 2020-11-28 09:19

I have a rest endpoint that returns a list on a GET call. I also have a POST endpoint to add new items and a DELETE to remove them. This works in Firefox and Chrome, and the

7条回答
  •  有刺的猬
    2020-11-28 09:37

    As answered above, 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 { HTTP_INTERCEPTORS } from '@angular/common/http'
      import { CacheInterceptor } from './cache-interceptor.service';
    
      // on providers
      providers: [{ provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true }]
    

提交回复
热议问题