angular - 如何使用 canDeactivate 与不在 ts 文件中的路由?
问题描述
我已经实现了防护并将其添加到相关路由中,例如路径:
]"quotes",
children: [ { path: "", component: QuotesComponent},
{ path: "create", component: CreateQuoteComponent, canDeactivate: [CanDeactivateGuard]},
{ path: ":id", component: CreateQuoteComponent, canDeactivate: [CanDeactivateGuard]}
我还在相关组件中添加了一个条件,例如:
canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
let agreeToLeave = false;
if (this.changesSaved === false) {
let message = 'You have not saved your current work and will lose changes. Are you want to proceed?';
let 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 => {
if (result) {
agreeToLeave = true;
return true;
}
});
return agreeToLeave;
}else{
return true;
}
}
每次单击任何按钮时,我都会看到模式窗口询问,但如果单击“是”,它不会转到相关页面。
同样,在我的情况下,所有路由都在 html 文件中,例如:
<mat-list-item [routerLink]="['/events']" routerLinkActive="activated">
<button mat-icon-button>
<mat-icon>comment</mat-icon>
</button>
非常感谢提前] 1
解决方案
你afterClosed()
是一个异步操作。事实上,它是一个 Promise。在模态关闭之前返回false
默认值。agreeToLeave
与其返回布尔值,不如简单地返回 Promise 本身。
canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
if (this.changesSaved) {
return true;
}
const message = 'You have not saved your current work and will lose changes. Are you want to proceed?';
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(); // if necessary map to boolean with map operator
}
编辑:为您的代码添加了一些改进
推荐阅读
- amazon-web-services - AWS SQS 为什么请求数量如此之高
- java - 在线程中运行时循环不起作用
- visual-studio - 从 msbuild 控制台构建切换到 IDE(第一次)时,VS 2017 会冗余构建代码
- php - 如何从 laravel 中的选择中使用 pluck() 选择多个列
- typescript - 我可以从具有类型谓词的函数中返回“void”吗?
- scim - 添加自定义属性的正确 SCIM 语法是什么
- python - 将初始 json 数据加载到 flask-sqlalchemy 项目时出现问题:sqlite3.InterfaceError: Error binding parameter 0 - 可能是不受支持的类型
- gradle - 让gradle在每次设置时执行一个finalizedBy任务(多次)
- php - 使用 eloquent 从多对多关系中获取数据
- javascript - 使用 marker.remove() 清除并再次添加标记