canDeactivate 不适用于 Angular 材质模态窗口

Tuv*_*sid 1 guard 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的组件中的一个函数:

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.
Run Code Online (Sandbox Code Playgroud)

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

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

  onSubmit(){
    this.dialogRef.close(true);
  }
Run Code Online (Sandbox Code Playgroud)

我尝试实现这个示例: How to send return value to CanDeactivate Guard after close the mat-dialog | Angular 可以停用 Guard | 角度材质对话框

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

use*_*584 10

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

首先,更改返回类型,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);
  }
}
Run Code Online (Sandbox Code Playgroud)

现在让更改component.confirmDialog方法返回可dialogRef.afterClosed()观察值,如下所示:

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();
  }
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。