Angular Ignore在下载文件时离开页面事件

问题描述 投票:1回答:1

在我的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)时,下载将触发窗口:beforeunload事件,浏览器将提醒enter image description here

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

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

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

javascript angular dom-events
1个回答
1
投票

你可以在守卫中定义一个标志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;
  }

  ...
}
© www.soinside.com 2019 - 2024. All rights reserved.