You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular即时通讯发送按钮问题:无法匹配对应Conversation ID

Angular 即时通讯工具发送按钮会话ID错误问题

问题场景

开发基于Angular的即时通讯工具,已实现用户标签页展示、切换查看聊天记录功能。发送消息API需message和conversationId两个参数,conversationId已获取并存入数组(如Cid = [1,2,3,4,5,6]),但点击不同用户标签页发送消息时,始终只用固定的一个conversationId(比如总是1),无法匹配当前会话的ID。

现有代码

TS文件

sendMessage(){

    if(!this.text){
      return;
    }

    let cid;

    for(let i=0; i<this.conversationID.length; i++){
      cid = this.conversationID[i]
    }

    console.log(cid);
    
    this.chatService.add(this.editor.quillEditor.root.innerHTML, cid);
    this.editor.quillEditor.root.innerHTML = '';
  }

Service文件

add(message: string, conversationId: number){

        const requestBody = {
            message,
            conversationId
        }

    
        this.http.post('createmessage', requestBody).subscribe((data) => {
            console.log(data);
        })
    
    }

HTML文件

<button class="ql-send-button" (click)="sendMessage()" [disabled]="!text"><fa-icon [icon]="faMessage"></fa-icon></button>

问题根源

sendMessage函数里的循环遍历conversationID数组毫无意义,循环结束后cid只会被赋值为数组的最后一个元素,完全没有关联当前选中标签页对应的会话ID。不管切换到哪个标签页,最终传入API的都是数组最后一项的ID,导致消息总是发送到固定会话。

修复方案

  1. 维护当前激活的会话ID:在组件中新增变量存储当前选中的会话ID,切换标签页时更新这个变量。

    activeConversationId: number;
    
    // 标签页点击切换会话的处理函数
    switchConversation(conversationId: number) {
      this.activeConversationId = conversationId;
      // 此处保留加载对应聊天记录的原有逻辑
    }
    
  2. 简化sendMessage函数:直接使用当前激活的会话ID,移除无效循环:

    sendMessage(){
        if(!this.text){
          return;
        }
    
        const cid = this.activeConversationId;
        // 增加判断,避免未选中会话时发送
        if (!cid) {
          console.warn('请先选择要聊天的用户');
          return;
        }
    
        console.log(cid);
        
        this.chatService.add(this.editor.quillEditor.root.innerHTML, cid);
        this.editor.quillEditor.root.innerHTML = '';
      }
    }
    
  3. 绑定标签页点击事件:确保点击标签页时传入对应会话ID,更新激活状态:

    <div 
      *ngFor="let conversation of conversations" 
      (click)="switchConversation(conversation.id)"
      [class.active-tab]="conversation.id === activeConversationId"
    >
      {{conversation.userName}}
    </div>
    

内容的提问来源于stack exchange,提问作者Abdullah Roshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 14:10:35