为什么我不能在取消订阅后再次订阅同一个EventEmitter

时间:2017-07-02 14:22:44

标签: angular typescript

我在组件(Angular2)的ngOnInit()中订阅,然后在ngOnDestroy()中取消订阅。在第二次初始化我的组件后,它给了我一个错误:

ObjectUnsubscribedError: object unsubscribed

在我的课上我有:

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

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

1 个答案:

答案 0 :(得分:7)

试试这段代码。

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