Mar*_*ers 5 angular2-router3 angular
我有一个确认/取消模式对话框,当用户离开路线时会弹出该对话框.我通过使用带有canDeactivate方法的后卫来做到这一点.但是我希望canDeactivate等到它返回任何东西之前从模态得到响应.
我试图通过返回一个observable来做到这一点,但它不起作用.
canDeactivate(): Observable<boolean> | boolean {
if(this.isFormStarted()) {
this.formService.showExitModal(true);
return this.formService.getModalSelectionObservable();
}
else {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
单击确认时没有发生任何事情,即使我在if块中执行console.log时可以看到observable工作正常
this.formService.getModalSelectionObservable().subscribe(
value => console.log("dialog value: " + value)
);
Run Code Online (Sandbox Code Playgroud)
以下是表单服务的外观.
private modalConfirmation = new Subject<boolean>();
public setModalSelectionObservable(confirmLeave: boolean) {
this.modalConfirmation.next(confirmLeave);
}
public getModalSelectionObservable(): Observable<boolean> {
return this.modalConfirmation.asObservable();
}
Run Code Online (Sandbox Code Playgroud)
使用take(1)或first()(别忘了导入)
return this.formService.getModalSelectionObservable().first();
Run Code Online (Sandbox Code Playgroud)
确保在第一个事件之后关闭observable,否则路由器将等待它从服务关闭.
| 归档时间: |
|
| 查看次数: |
3910 次 |
| 最近记录: |