取消订阅不是 Angular 16 中的函数

Unsubscribe is not a function in Angular 16

提问人:themadhatter 提问时间:11/13/2023 最后编辑:Heretic Monkeythemadhatter 更新时间:11/13/2023 访问量:55

问:

这是服务中的代码

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

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

  }

我这样做是为了防止函数似乎一次又一次地被调用

enter image description here

但是在这样做时,我得到了错误


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)

为什么会发生此错误?如何纠正?

节点.js Angular TypeScript socket.io

评论

0赞 Saidamir 11/13/2023
我看出你的代码没有问题,你能尝试像这样取消 sunbscribe 吗ngOnDestroy(): void { this.getMsgSubscription?.unsubscribe(); }
0赞 themadhatter 11/13/2023
不幸的是,我仍然遇到同样的错误
1赞 MoxxiManagarm 11/13/2023
这回答了你的问题吗?订阅不是一个函数 Angular / Socket.IO

答:

0赞 MGX 11/13/2023 #1

您无法取消订阅主题。

您可以使用以下两种方式:

this.getMsgSubscription.complete();

要关闭它,或者当您订阅时,请使用

this.getMsgSubscription.asObservable().subscribe().unsubscribe();

将其转换为您取消订阅的可观察对象。

评论

0赞 themadhatter 11/14/2023
谢谢,我发现这与我从 stackoverflow.com/questions/38008334/ 那里得到的方法一起工作......