首页 > 解决方案 > canDeactivate 不适用于 Angular 材质模态窗口

问题描述

我成功地构建了 canDeactivate 保护,它在正常确认下工作正常,但我想用角度材料对话框来实现它,在这里我遇到了一些问题。

这是我的后卫:

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CreateQuoteComponent> {
  constructor(
    public dialog: MatDialog,
  ){

  }
  canDeactivate(component: CreateQuoteComponent): boolean {
    if (!component.changesSaved) {
      return component.confirmDialog();
      //return confirm('You have not saved your current work. Do you want to proceed and discard your changes?');
    }
    return true;
  }
}

这是我的组件中的一个功能:

confirmDialog(): boolean {
    const message = 'You have not saved your current work. Do you want to proceed and discard?';
    const data = { 'message': message, 'toShowCancel': true, 'buttonYesCaption': 'Yes', 'buttonNoCaption': 'No' };
    const dialogRef = this.dialog.open(YesNoComponent, {
      width: '600px',
      height: '250px',
      data: data
    });
    dialogRef.afterClosed().subscribe(result=>{
      this.dialogRef1=result;
      return this.dialogRef1;
    });
    return this.dialogRef1;
  }

 I defined a boolean variable dialogRef1 at the top of the component.

它是带有模态窗口的组件的一部分:

onCloseClick(){
    this.dialogRef.close(false);
  }

  onSubmit(){
    this.dialogRef.close(true);
  }

我试图实现这个例子: 关闭 mat-dialog 后如何将返回值发送到 CanDeactivate Guard | Angular CanDeactivate Guard | 角度材料对话框

但这对我不起作用,或者我做错了。提前致谢!

标签: angularguard

解决方案


您正在返回一个dialogRef.afterClosed()由用户决定的 Observable [ie ] 设置的变量值。您应该执行以下操作:

canDeactivate首先,像Observable<boolean>这样更改返回类型:

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CreateQuoteComponent> {
  constructor(
    public dialog: MatDialog,
  ){

  }
  canDeactivate(component: CreateQuoteComponent): Observable<boolean> {
    if (!component.changesSaved) {
      return component.confirmDialog();      
    }
    //please import 'of' form 'rxjs/operators'
    return of(true);
  }
}

现在让我们更改component.confirmDialog方法以返回dialogRef.afterClosed()observable,如下所示:

confirmDialog(): Observable<boolean> {
    const message = 'You have not saved your current work. Do you want to proceed and discard?';
    const data = { 'message': message, 'toShowCancel': true, 'buttonYesCaption': 'Yes', 'buttonNoCaption': 'No' };
    const dialogRef = this.dialog.open(YesNoComponent, {
      width: '600px',
      height: '250px',
      data: data
    });
    return dialogRef.afterClosed();
  }

希望能帮助到你。


推荐阅读