【发布时间】:2019-10-16 14:45:07
【问题描述】:
我在组件中有一个函数来检查我是否可以通过评估表单状态来离开路线。 如果状态与我需要要求离开路线的条件匹配,则会显示一个对话框以确认或取消。 我在我的 canDeactivate 服务中调用了这个函数,但它在等待对话确认之前触发了响应。
我已经在 canDeactivate 服务中添加了一个console.log 和组件的功能。 当不需要确认时,它按预期显示为真。但另一方面,当需要确认时,它会在对话框出现之前显示未定义。
canDeactivateService.ts
@Injectable()
export class ProdutosDeactivateGuard implements CanDeactivate<ExampleComponent> {
canDeactivate(
component: ExampleComponent,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
return component.checkStatus();
}
}
example-component.ts
checkStatus() {
if (!this.form.pristine && this.form.touched) {
const dialogRef = this.dialog.open(DeactivateDialogComponent);
dialogRef.afterClosed().subscribe(result => {
if (result === 'true') {
return true;
} else {
return false;
}
});
} else {
return true;
}
}
}
我希望服务等待确认。我怎么能这样做?
【问题讨论】:
-
component.checkStatus()是否在守卫内正确返回值? -
@Arcteezy 这是问题所在。当不需要对话框时,它会正确返回。但是当需要对话框时,守卫在等待函数响应之前触发返回。
标签: angular asynchronous angular-material modal-dialog candeactivate