Return Observable in canDeactivate not working

前端 未结 3 1532
旧巷少年郎
旧巷少年郎 2020-12-18 02:59

I have a confirm/cancel modal dialog that pops up when a user leaves a route. I do this by using a guard with the canDeactivate method. However I want canDeactivate to wait

相关标签:
3条回答
  • 2020-12-18 03:21

    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.

    0 讨论(0)
  • 2020-12-18 03:31

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-18 03:48

    It was not working on my end because I was using BehaviorSubject with initial value null.

    Make sure to create Observable from Subject like:

    private modalConfirmation = new Subject<boolean>();
    public getModalSelectionObservable(): Observable<boolean> {
        return this.modalConfirmation.asObservable();
    }
    
    0 讨论(0)
提交回复
热议问题