2016-07-22 81 views
4

我有一个确认/取消模式对话框,用户离开路线时弹出。我通过使用canDeactivate方法使用警卫来做到这一点。不过,我希望canDeactivate能够在返回任何内容之前等待模态响应。返回在canDeactivate中可观察不起作用

我试图通过返回一个可观察的,但它不工作。当我点击确认,即使我可以看到,可观察工作正常,当我做内的console.log

canDeactivate(): Observable<boolean> | boolean { 
    if(this.isFormStarted()) { 
     this.formService.showExitModal(true); 
     return this.formService.getModalSelectionObservable(); 
    } 
    else { 
     return true; 
    } 
} 

什么也没发生的,如果块

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(); 
} 
+0

这是为什么你正在使用2个不同的服务,在你的'canDeactivate'功能:'this.formService'和'this.createFormService'? –

+0

是的,他们应该是一样的,我已经更新了,谢谢。我只是改变了变量名称,以便在这里更有意义。 –

+0

嗨马克,如何设法让你的模态等待用户的回应?你能分享你的解决方案吗?我面临同样的问题。亲切的问候 –

回答

7

使用take(1)first()(不要忘记导入)

return this.formService.getModalSelectionObservable().first(); 

,以保证观察到的第一个事件后关闭,否则路由器将等待,直到它从服务关闭。

+0

嗨Gunter,你能解释我如何'getModalSelectionObservable'应该工作?我面临同样的问题,我不知道如何使刷新等待模态的结果。 –

+0

我不知道'getModalSelectionObservable()'。我只知道'canDeactivate' –

+0

我看到...我正面临着canDeactivate这个问题...我无法使用服务显示自定义消息或对话... [请参阅我的问题](http:// stackoverflow.com/questions/42142053/candeactivate-confirm-message)..可以帮助我吗? –

0

在未来的只是把这个位置的情况下,有人不小心的我:

如果组件有一个功能hasUnsavedChanges()canDeactivate()方法将需要返回!hasUnsavedChanges()

但是,如果您开始使用hasUnsavedChanges的可观察值,那么您将返回!hasUnsavedChanges$,这将只是一个虚假值。

如果你需要同时支持你可以这样做:

canDeactivate(component: C) 
{ 
    var hasUnsavedChanges = component.hasUnsavedChanges(); 

    if (typeof (hasUnsavedChanges) === 'boolean') 
    { 
     return !hasUnsavedChanges; 
    } 
    else 
    { 
     return hasUnsavedChanges.map(x => !x); 
    } 
}