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



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

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

谢谢,Gerry

使用元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">

或者,

http请求中添加headers为:-

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

HTTPInterceptors是修改应用程序中发生的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);
}
}

使用拦截器:

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 { }

如何在url:中添加盐

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

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

/static/some-file.css?{一些随机符号}

我使用date是因为它保证了我的数字是唯一的,而不使用随机等等。我们也可以对每个调用使用递增整数。

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

根据Pramod的回答,您可以使用http请求拦截器修改或设置请求的新标头。以下是一种更简单的方法,用于为以后的角度版本(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 }]

最新更新