How to disable caching with HttpClient get in Angular 6

后端 未结 4 1163
感动是毒
感动是毒 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:09

    HTTPInterceptors are great way to modify HTTP requests occurring in your application. It acts as an injectable service that can invoke when HttpRequest occurs.

    HTTP Interceptor:

    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpRequest, HttpHandler, HttpHeaders } from '@angular/common/http';
    
    @Injectable()
    export class CacheInterceptor implements HttpInterceptor {
    
      intercept(req: HttpRequest, next: HttpHandler) {
        const httpRequest = req.clone({
          headers: new HttpHeaders({
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
          })
        });
    
        return next.handle(httpRequest);
      }
    }
    

    Using Interceptor:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    
    import { AppComponent } from './app.component';
    
    import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
    import { CacheInterceptor } from './http-interceptors/cache-interceptor';
    
    @NgModule({
      imports:      [ BrowserModule, FormsModule ],
      declarations: [ AppComponent ],
      bootstrap:    [ AppComponent ],
      providers: [
        { provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true }
      ]
    })
    export class AppModule { }
    

提交回复
热议问题