如何防止或避免Angular 2+;应用?
我有这样一种情况,我将参数发送到一个API,该API反过来生成动态pdf&API将新生成的文件的路径发送给我。当我在浏览器中打开文件时,它会显示新生成的文件,但在我的DOM中,我仍然会看到旧文件,直到我关闭浏览器并再次点击API为止。我正在预览生成的pdf文件,如下所示: TS部分:如何防止或避免Angular 2+;应用?,angular,pdf,angular6,browser-cache,cache-control,Angular,Pdf,Angular6,Browser Cache,Cache Control,我有这样一种情况,我将参数发送到一个API,该API反过来生成动态pdf&API将新生成的文件的路径发送给我。当我在浏览器中打开文件时,它会显示新生成的文件,但在我的DOM中,我仍然会看到旧文件,直到我关闭浏览器并再次点击API为止。我正在预览生成的pdf文件,如下所示: TS部分: this.http.postMethod("report/auditAdmin", data).subscribe((res: any) => { this.toolbar = "#toolb
this.http.postMethod("report/auditAdmin", data).subscribe((res: any) => {
this.toolbar = "#toolbar=0&navpanes=0";
this.pdfSrc = res.filepath + this.toolbar;
this.Url = this.sanitizer.bypassSecurityTrustResourceUrl(this.pdfSrc);
});
HTML部分:
<object [data]="Url" type="application/pdf" width="100%" height="1000px"></object>
要防止/避免Angular 2+版本中的缓存,您可以通过覆盖RequestOptions来实现
import { Injectable } from '@angular/core';
import { BaseRequestOptions, Headers } from '@angular/http';
@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
headers = new Headers({
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
});
}
步骤1:创建自定义请求选项
import { Injectable } from '@angular/core';
import { BaseRequestOptions, Headers } from '@angular/http';
@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
headers = new Headers({
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
});
}
步骤2在RootAppModule.ts中提供
@NgModule({
...
providers: [
...
{ provide: RequestOptions, useClass: CustomRequestOptions }
]
})
希望以上解决方案能解决您的问题 问题不在于API缓存或角度,而在于对象控件。
当我们尝试加载数据(如pdf文件或任何其他外部内容)时,对象会发送一个获取请求,以显示内容(可以在浏览器的“网络”选项卡中查看获取请求)
因此,简单的解决方案是将querystring附加到pdf路径
this.http.postMethod("report/auditAdmin", data).subscribe((res: any) => {
this.toolbar = "#toolbar=0&navpanes=0";
let ramdom = Math.random();
this.pdfSrc = res.filepath + "?v=" + random + this.toolbar;
this.Url = this.sanitizer.bypassSecurityTrustResourceUrl(this.pdfSrc);
});
现在,每当您的对象尝试对pdf文件发出get请求时,由于querystring,每个请求都将是新的,因此不会从缓存加载数据。URL总是相同的还是不同的?总是在同一主机上,所以它是不同的?如果是这样,那么缓存就不是问题,您需要创建一个新的对象
元素。如果是这样的话,你可以通过添加一个随机参数来解决这个问题。是的,我想过添加随机参数,但这会创建多个pdf&我想在每次用户来自其ip地址时替换pdf