angular – 在canDeactivate中返回Observable不起作用
发布时间:2020-12-17 17:50:51 所属栏目:安全 来源:网络整理
导读:我有一个确认/取消模式对话框,当用户离开路线时会弹出该对话框.我通过使用带有canDeactivate方法的后卫来做到这一点.但是我希望canDeactivate等到它返回任何东西之前从模态得到响应. 我试图通过返回一个observable来做到这一点,但它不起作用. canDeactivate(
我有一个确认/取消模式对话框,当用户离开路线时会弹出该对话框.我通过使用带有canDeactivate方法的后卫来做到这一点.但是我希望canDeactivate等到它返回任何东西之前从模态得到响应.
我试图通过返回一个observable来做到这一点,但它不起作用. canDeactivate(): Observable<boolean> | boolean { if(this.isFormStarted()) { this.formService.showExitModal(true); return this.formService.getModalSelectionObservable(); } else { return true; } } 单击确认时没有发生任何事情,即使我在if块中执行console.log时可以看到observable工作正常 this.formService.getModalSelectionObservable().subscribe( value => console.log("dialog value: " + value) ); 以下是表单服务的外观. private modalConfirmation = new Subject<boolean>(); public setModalSelectionObservable(confirmLeave: boolean) { this.modalConfirmation.next(confirmLeave); } public getModalSelectionObservable(): Observable<boolean> { return this.modalConfirmation.asObservable(); } 解决方法
使用take(1)或first()(不要忘记导入)
return this.formService.getModalSelectionObservable().first(); 确保在第一个事件之后关闭observable,否则路由器将等待它从服务关闭. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |