angular - 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 | 角度材料对话框
但这对我不起作用,或者我做错了。提前致谢!
解决方案
您正在返回一个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();
}
希望能帮助到你。
推荐阅读
- java - 即使添加了 jackson-modules-java8 依赖项,也找不到 Jackson JavaTimeModule?
- c# - 在 EF6 中构建高效的左反半连接
- angular - 在活动选项卡上运行回调的 ClrTabs 更改事件而不是显示内容
- javascript - Javascript concat 方法的结果顺序
- dask - 在不占用工人的情况下休眠的 Dask 功能?
- excel - 引用单元格的自定义 Excel 格式
- java - 在两个部分不同的 ArrayList 之间传输数据
- python - 在不同线程的类之间传递变量?
- ruby-on-rails - 如何安装 d3-rails gem?
- prometheus - 我怎样才能在普罗米修斯中删除除少数列入白名单的指标之外的所有指标?