Angular2 CanDeactivate with Asynchronous Observable

I look at the guards and try to prevent navigation from CanDeactivate. I want to show an easy way with Save / Cancel, save = navigate and well, cancel = cancel.

I have CanDeactivate, but it seems that it was not resolved at the right time

Guard.ts

canDeactivate(component: PortfolioModelComponent) {
    component.saveChanges(); // Opens modal
    return component.modalResponse.take(1); // isnt happening at the right time
}

Componentent.ts

 public modalResponse: Observable<boolean> = new Observable((observer) => { });

public saveChanges() {
    this.openSaveChangeModal();
}

// Modal save changes
public openSaveChangeModal() {
    $('#savePortfolioChangesModal').modal();
}

public closeSaveChangesModal() {
     this.modalResponse = new Observable((observer) => {
        observer.next(false);
    });
    $('#savePortfolioChangesModal').modal('hide');
}

public saveSaveChangesModal() {
    this.modalResponse = new Observable((observer) => {
        observer.next(true);
    });
    $('#savePortfolioChangesModal').modal('hide');
}

In the first "Save" nothing happens when the modal is displayed. In the second “Save” navigation will happen before I answer the modal. How can I solve the problem at the right time?

+4
source share

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


All Articles