Return Observable in canDeactivate not working

不打扰是莪最后的温柔 提交于 2019-11-29 10:51:15

Use take(1) or first() (don't forget to import)

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

to ensure the observable is closed after the first event, otherwise the router will wait until it is closed from the service.

Just putting this here in case someone in future is as careless as me:

If your component has a function hasUnsavedChanges() your canDeactivate() method would need to return !hasUnsavedChanges().

But then if you start using an observable for hasUnsavedChanges, you'll be returning !hasUnsavedChanges$ which will just be a falsey value.

If you need to support both you can do this:

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

    if (typeof (hasUnsavedChanges) === 'boolean')
    {
        return !hasUnsavedChanges;
    }
    else
    {
        return hasUnsavedChanges.map(x => !x);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!