在我的 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;
}
...
}
关于javascript - 下载文件时Angular忽略离开页面事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671378/