Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - Return Observable in canDeactivate not working

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 until it gets a response from the modal before returning anything.

I have tried to do this by returning an observable but it is not working.

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

Nothing is happening when I click confirm even though I can see that the observable is working fine when I do a console.log inside the if block

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

Here is how the form service looks.

private modalConfirmation = new Subject<boolean>();

public setModalSelectionObservable(confirmLeave: boolean) {
    this.modalConfirmation.next(confirmLeave);
}
public getModalSelectionObservable(): Observable<boolean> {
    return this.modalConfirmation.asObservable();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...