如何在Angular 6中使用HttpClient禁用缓存

Ger*_*rry 15 caching httpclient angular

我正在编写一个Angular SPA应用程序,该应用程序使用HttpClient从后端获取值。

告诉它不缓存的简单方法是什么?我第一次要求它获取值,然后它拒绝进行后续查询。

谢谢,格里

Mah*_*ahi 22

使用元HTML标记,禁用浏览器缓存:-

<meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0">
<meta http-equiv="expires" content="0">
<meta http-equiv="pragma" content="no-cache">
Run Code Online (Sandbox Code Playgroud)

要么,

添加headershttp要求如下: -

headers = new Headers({
        'Cache-Control':  'no-cache, no-store, must-revalidate, post- 
                            check=0, pre-check=0',
        'Pragma': 'no-cache',
        'Expires': '0'
    });
Run Code Online (Sandbox Code Playgroud)


gro*_*ont 18

在 url 中添加盐怎么样:

const salt = (new Date()).getTime();
return this.httpClient.get(`${url}?${salt}`, { responseType: 'text' });
Run Code Online (Sandbox Code Playgroud)

html(css 或 js)中的静态资源链接也使用相同的概念来欺骗缓存。在url中添加动态盐会导致每次重新加载目标,因为url每次都不同,但实际上是相同的。

/static/some-file.css?{some-random-symbols}

我使用日期是因为它保证我唯一的数字而不使用随机等。我们也可以为每次调用使用递增整数。

如果我无法更改服务器配置,上面提供的代码对我来说效果很好。


Pra*_*ali 10

HTTPInterceptor是修改应用程序中发生的HTTP请求的好方法。它充当可注入服务,可以在HttpRequest发生时调用。

HTTP拦截器:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpHeaders } from '@angular/common/http';

@Injectable()
export class CacheInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

使用拦截器:

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 { }
Run Code Online (Sandbox Code Playgroud)


Joh*_*red 7

正如 Pramod 所回答的,您可以使用 http 请求拦截器来修改或设置请求的新标头。下面是为更高的 Angular 版本( Angular 4+ )在 http 请求拦截器上设置标头的更简单的方法。这种方法只会设置或更新某个请求标头。这是为了避免删除或覆盖一些重要的标头,例如授权标头。

// 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<any>, 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 }]
Run Code Online (Sandbox Code Playgroud)

  • 这与@Pramod 的答案几乎完全相同 (5认同)
  • @CoenDamen 不,它不完全相同。Pramod 的答案使用新的 Header 实例化,而此答案重用从 req 变量发送的相同标头并使用 .set() 方法添加无缓存策略 (2认同)