Refund Observed in canDeactivate not working

I have a modality confirmation / cancellation dialog box that appears when the user leaves the route. I do this using security with the canDeactivate method. However, I want canDeactivate to wait until it receives a response from the modality before returning anything.

I tried to do this by returning the observable, but it does not work.

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

Nothing happens when I press the confirmation button, although I can see that the observable works fine when I do console.log inside the if block.

this.formService.getModalSelectionObservable().subscribe(
        value => console.log("dialog value: " + value)
    );

This is what the form service looks like.

private modalConfirmation = new Subject<boolean>();

public setModalSelectionObservable(confirmLeave: boolean) {
    this.modalConfirmation.next(confirmLeave);
}
public getModalSelectionObservable(): Observable<boolean> {
    return this.modalConfirmation.asObservable();
}
+4
source share
2 answers

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

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

, , , .

+7

, - , :

hasUnsavedChanges(), canDeactivate() !hasUnsavedChanges().

, hasUnsavedChanges, !hasUnsavedChanges$, .

, :

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

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

Source: https://habr.com/ru/post/1648764/


All Articles