2017-09-14 201 views
0

我爲我的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

您可以將訂閱保存到變量並在獲取所需內容後使用它來取消訂閱。就像這樣:

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 
    }); 
});