【问题标题】:How to prevent or avoid Cache in Angular 2 + Applications?如何防止或避免 Angular 2 + 应用程序中的缓存?
【发布时间】:2026-02-10 03:20:02
【问题描述】:

我有一种情况,我将参数发送到 API,然后 API 会生成动态 pdf,API 会向我发送新生成文件的路径。当我在浏览器中打开文件时,它会显示新生成的文件,但在我的 DOM 中,我仍然看到旧文件,除非我关闭浏览器并再次点击 API。我正在预览生成的pdf文件如下:

TS 部分:

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>

【问题讨论】:

  • 网址总是相同还是不同?
  • 始终在同一主机上
  • 所以不一样了?如果是这样,那么缓存不是问题,您需要创建一个新的object 元素。如果是这样,您可以通过向其添加随机参数来解决问题。
  • 是的,我想过添加随机参数,但这会创建多个 pdf 并且我想在每次用户来自他的 IP 地址时替换 pdf

标签: angular pdf angular6 browser-cache cache-control


【解决方案1】:

问题不在于 API 缓存或 Angular,问题在于对象控制。 当我们尝试加载 pdf 文件或任何其他外部内容对象等数据时,会发送 get 请求 来显示内容(get 请求可以在浏览器的网络选项卡中查看)。

所以简单的解决方案是将查询字符串附加到您的 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 请求时,每个请求都会因为查询字符串而变得新鲜,因此不会从缓存中加载数据。

【讨论】:

    【解决方案2】:

    要防止/避免 Angular 2+ 版本中的缓存,您可以通过覆盖 RequestOptions 来实现。

    第 1 步:创建自定义 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'
        });
    }
    

    第 2 步在 Root 中提供 AppModule.ts

    @NgModule({
        ...
        providers: [
            ...
            { provide: RequestOptions, useClass: CustomRequestOptions }
        ]
    })
    

    希望以上解决方案能解决您的问题!

    【讨论】: