繁体   English   中英

下载文件时Angular忽略离开页面事件

[英]Angular Ignore leave page event when download file

在我的 Angular 7 应用程序中,我有一个 canDeactivate 防护来提醒用户未保存的更改。 这个守卫也防止离开页面

  @HostListener('window:beforeunload')
  public canDeactivate(): boolean {
    return this.contentChanged === false;
  }

在同一页面上,我有一些功能可以从 AWS S3 下载

  async downloadAttachment(url: string, e: any) {
    const target = e.target || e.srcElement || e.currentTarget;
    window.onbeforeunload = null;
    if (!target.href) {
      e.preventDefault();
      target.href = await this.storageService.getDownloadLink(
        url,
      );
      target.download = this.storageService.getFileName(url);
      target.click();
    }
  }

问题是当我有未保存的更改(contentChanged=true)时,下载将触发 window:beforeunload 事件并且浏览器会发出警报在此处输入图片说明

用户必须单击“离开”才能下载文件。 下载过程实际上并没有离开页面。

我试图在代码中添加“window.onbeforeunload = null”,但它在我的代码中不起作用。

如何允许用户下载而不会看到无意义的警报?

您可以在警卫中定义一个标志isDownloadingFile ,并在开始下载之前设置它:

constructor(private canDeactivateGuard: CanDeactivateGuard) { }

async downloadAttachment(url: string, e: any) {
  const target = e.target || e.srcElement || e.currentTarget;
  if (!target.href) {
    e.preventDefault();
    this.canDeactivateGuard.isDownloadingFile = true; // <---------------- Set flag
    target.href = await this.storageService.getDownloadLink(url);
    target.download = this.storageService.getFileName(url);
    target.click();
  }
}

然后,您将在canDeactivate检查并重置该标志:

@Injectable()
export class CanDeactivateGuard {

  public isDownloadingFile = false;

  @HostListener('window:beforeunload')
  public canDeactivate(): boolean {
    const result = this.isDownloadingFile || !this.contentChanged; // <--- Check flag
    this.isDownloadingFile = false; // <---------------------------------- Reset flag
    return result;
  }

  ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM