我为Angular 4表单创建了一个canDeactivate处理程序。虽然这有效,但我担心我会导致内存泄漏(因为没有更好的术语)。我读到你必须取消订阅以避免不断增加的订阅列表;但是我不知道在哪里/如何取消订阅我在下面创建的订阅。 observer.complete调用是否会删除订阅?
// 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();
});
});
}
答案 0 :(得分:1)
您可以将订阅保存到变量中,并在获得所需内容后使用它来取消订阅。像这样:
return Observable.create(observer => {
let subscription = this.dialogWindow.observable.subscribe(buttonPressed => {
const proceed = (buttonPressed === EButtonPressed.EButtonPressedYes);
console.log('Allow proceed: ' + proceed);
observer.next(proceed);
observer.complete()
subscription.unsubscribe(); // here you unsubscribe
});
});