【问题标题】:canDeactivate doesn't work with Angular material modal windowcanDeactivate 不适用于 Angular 材质模态窗口
【发布时间】:2020-01-05 03:43:44
【问题描述】:

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

这是我的守卫:

@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);
  }

我试图实现这个例子: How to send return value to CanDeactivate Guard after close the mat-dialog | Angular CanDeactivate Guard | Angular Material Dialog

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

【问题讨论】:

    标签: angular guard


    【解决方案1】:

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

    首先,将canDeactivate 的返回类型更改为Observable&lt;boolean&gt;,如下所示:

    @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();
      }
    

    希望对你有帮助。

    【讨论】:

    • 它正在工作!如果你住在奥克兰,我会为你买杯咖啡:)
    猜你喜欢
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多