我在组件(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();
}
答案 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();
}
}