Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();  
}
like image 875
Юра Арабчук Avatar asked Oct 22 '25 11:10

Юра Арабчук


1 Answers

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();  
        }
    }
like image 174
Sreemat Avatar answered Oct 24 '25 06:10

Sreemat