Юра Арабчук Юра Арабчук - 5 months ago 41
TypeScript Question

Why can't i subscribe again on that same EventEmitter after unsubscribe

I subscribe in ngOnInit() of a component (Angular2) and then unsubscribe in ngOnDestroy(). After second initializing of my component it gives me an error:

ObjectUnsubscribedError: object unsubscribed


In my class i have:

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

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

Answer Source

Try this code.

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