2017-07-02 97 views
-1

我在組件(Angular2)的ngOnInit()中訂閱,然後在ngOnDestroy()中取消訂閱。我的組件的第二初始化後,它給我一個錯誤:爲什麼我不能在取消訂閱後在同一個EventEmitter上訂閱

ObjectUnsubscribedError: object unsubscribed 

在我的課,我有:

ngOnInit() { 
    this.chatService.getConversationsEvent() 
    .subscribe((data:Data<Array<Conversation>>) => { 
     console.log('from correspondence'); 
    }); 
    this.scrollToBottom(); 
} 

ngOnDestroy() { 
    this.chatService.getConversationsEvent().unsubscribe(); 
} 
+1

這裏添加一些代碼 – Sreemat

+0

添加的代碼有點 –

回答

1

試試這個代碼。

chatObservable:any;  
ngOnInit() { 
     this.chatObservable=this.chatService.getConversationsEvent() 
     .subscribe((data:Data<Array<Conversation>>) => { 
      console.log('from correspondence'); 
     }); 
     this.scrollToBottom(); 
    } 

    ngOnDestroy() { 
     if(!chatObservable.closed()){ 
     this.chatObservable.unsubscribe(); 
     } 
    } 
+0

似乎是工作,我要檢查它carefuly,如果它的作品,我會率你。而且在ngOnDestroy中,你會錯過this.chatObservable。我只是新來的,不知道如何編輯它。 –

+0

謝謝你,你是最棒的。主要觀點是新變量chatObservable並從該變量你必須退訂! –

+0

Cool @ЮраАрабчук – Sreemat