Angular 11: 使 canDeactivate observable 等待嵌套函数

Angular 11: Make canDeactivate observable wait for nested function

我正在尝试使用 Material 对话框将我的浏览器警报替换为自定义警报。如果用户试图离开具有未保存更改的表单,则会显示自定义警报。但我需要等待(暂停功能),直到用户单击一个选项以 return 值。

discardChangesAlertResult: boolean;

canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
    if (this.hasBeenEdited) {

        const dialogRef = this.dialog.open(DiscardChangesComponent, {panelClass: 'alert'});
        
        dialogRef.afterClosed().subscribe(result => {
            if (this.discardChangesService.discardChangesAlert) {
                this.hasBeenEdited = false;
                this.discardChangesAlertResult = true;
            } else {
                this.discardChangesAlertResult = false;
            } 
        });

        return this.discardChangesAlertResult; // I need this line to wait for user input
    } else {
        return true;
    }
}

你必须 return Observable 为此。

canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
    if (!this.hasBeenEdited) {
        return true;
    }
    return this.dialog
        .open(DiscardChangesComponent, {panelClass: 'alert'})
        .afterClosed()
        .pipe(map(result => {
            if (this.discardChangesService.discardChangesAlert) {
                this.hasBeenEdited = false;
            }
            return !!this.discardChangesService.discardChangesAlert;
        });
}