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

时间:2019-04-14 01:59:46

标签: javascript angular dom-events

在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事件,并且浏览器将发出警报 enter image description here

,用户必须单击“离开”以下载文件。下载过程实际上不会离开该页面。

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

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

1 个答案:

答案 0 :(得分: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;
  }

  ...
}