我成功构建了canDeactivate guard,它在正常确认下工作正常,但我想通过角度材料对话框实现它,在这里我遇到了一些问题。
这是我的卫兵:
@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);
}
我试图实现这个例子: 如何在关闭垫子对话框后将返回值发送到 CanDeactivate Guard |角烛停用防护罩 |"角度材料"对话框
但它对我不起作用,或者我做错了。提前感谢!
您返回的变量值由可观察量 [即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);
}
}
现在让我们更改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();
}
希望对您有所帮助。