2017-09-14 83 views
1

我为我的表单创建了一个简单的canDeactivate处理程序。当我试图离开我的表单时,下面的函数会运行,并且我可以根据单击的按钮确认订阅返回TRUE或FALSE。但无论订阅的结果如何,Angular永远不会离开我的表单。有人能解释为什么吗?Angular 4 canDeactivate不尊重选择

public canDeactivate(): Subscription { 
    // Popup a prompt dialog 
    const title = 'Lose Changes'; 
    const prompt = 'Are you sure you want to lose your changes'; 
    this.dialogWindow.show(EDialogTypes.EDialogYesNo, EDialogStyles.EDialogStyleWarning, title, prompt); 

    // Based on the result allow leave or not 
    this.subscription = this.dialogWindow.observable.subscribe(proceed => { 
    console.log('Allow proceed: ' + proceed) 
    console.log(this.dialogWindow.buttonPressed); 
    // unsubscribe is necessary such that the observable doesn't keep racking up listeners 
    this.subscription.unsubscribe(); 
    return proceed; 
    }); 
    return this.subscription; 
} 

回答

0

我设法弄清楚一些基于其他SO问题的东西。

// Allow the user to navigate away from this page 
public canDeactivate(): Observable<boolean> { 

    // Popup a prompt dialog 
    const title = 'Lose Changes'; 
    const prompt = 'Are you sure you want to lose your changes?'; 
    this.dialogWindow.show(EDialogTypes.EDialogYesNo, EDialogStyles.EDialogStyleWarning, title, prompt); 

    return Observable.create(observer => { 
    this.dialogWindow.observable.subscribe(buttonPressed => { 
     const proceed = (buttonPressed === EButtonPressed.EButtonPressedYes); 
     console.log('Allow proceed: ' + proceed); 
     observer.next(proceed); 
     observer.complete(); 
    }); 
    }); 
}