Issue
This is the code in service
getMsg(users_data: any): Subscription {
return this.socket.on('loadNewChat', async (data: any) => {
if(users_data.user1._id===data.sender_id && users_data.user2._id===data.reciever_id){
const container = document.getElementById('chat-container');
const element = document.createElement('ul');
if (this.msg !== data.message) {
element.innerHTML = data.message;
element.style.textAlign = 'right';
container!.appendChild(element);
}
}
});
}
This is how it is in component.ts
private getMsgSubscription: Subscription = new Subscription();
ngOnInit(): void {
this.dialogdata = this.data
this.UserData.sender_id = this.dialogdata.user2._id
this.UserData.reciever_id = this.dialogdata.user1._id
this.getMsgSubscription = this.sockservice.getMsg(this.dialogdata)
this.sockservice.getChats(this.UserData)
}
ngOnDestroy(): void {
if (this.getMsgSubscription!== undefined) {
this.getMsgSubscription.unsubscribe();
}
}
I am doing this to prevent the where the function seems to be called again and again
But while doing so I get the error
chatview.component.ts:39 ERROR TypeError: this.getMsgSubscription.unsubscribe is not a function
at ChatviewComponent.ngOnDestroy (chatview.component.ts:58:31)
at executeOnDestroys (core.mjs:7359:32)
at cleanUpView (core.mjs:7267:9)
at destroyViewTree (core.mjs:7095:21)
at destroyLView (core.mjs:7245:9)
at RootViewRef.destroy (core.mjs:13738:9)
at ComponentRef.destroy (core.mjs:14195:23)
at DomPortalOutlet._disposeFn (portal.mjs:321:30)
at DomPortalOutlet._invokeDisposeFn (portal.mjs:217:18)
at DomPortalOutlet.detach (portal.mjs:201:14)
Why does this error happen? How to correct it?
Solution
You cannot unsubscribe from a subject.
You can either use this :
this.getMsgSubscription.complete();
To close it, or when you subscribe, use
this.getMsgSubscription.asObservable().subscribe().unsubscribe();
To convert it to an observable that you unsubscribe from.
Answered By - MGX
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.