我如何使用 socket.io-client 在 angular 的不同端显示发送者和接收者消息

How i can display sender and receiver message on different side in angular using socket.io-client

一切正常,但问题是我想在不同的一侧显示发送者和接收者消息,但我不知道如何实现这一点,我也从服务器端获取套接字 ID,但我我无法创建逻辑,如何在我的 html 页面上区分发件人和收件人消息 请任何人帮助我 提前致谢

这是我的服务器端代码

 io.on('connection', (socket) => {
 console.log('a user connected');
 socket.emit('myId', socket.id);

 socket.on('sendMessage', (message) => {
  const sockitID = socket.id;
  console.log(sockitID);
  io.emit('recieveMessage', message); //`${socket.id.substr(0, 2)} said--${message}`
 });

 socket.on('disconnect', () => {
  console.log('a user disconnected!');
 });
 });

这是我在 agular 端的 chatserivce 文件

  import { Injectable, OnInit } from '@angular/core';
  import { BehaviorSubject, Observable } from 'rxjs';
  import { io, Socket } from "socket.io-client";
  import { DefaultEventsMap } from 'socket.io-client/build/typed-events';
  import { MessageModel } from './app.component';

  @Injectable({
  providedIn: 'root'
  })
  export class ChatService implements OnInit {
    public message$: BehaviorSubject<MessageModel> = new BehaviorSubject({});
    public socket: Socket<DefaultEventsMap, DefaultEventsMap>;
    public socketID: string = ''
    constructor() {
     this.socket =io('http://localhost:3000');
     this.socket.on('myId', (id)=>{
     console.log('from service',id);
    });

    }
   ngOnInit(): void {

   }
   public sendMessage(message:any) {
     this.socket.emit('sendMessage', {message: message, senderId : this.socketID});
     const senderID = this.socket.id;
     console.log('Sender ID = ' ,senderID);
   }

   public getNewMessage = () => {
    this.socket.on('recieveMessage', (message) =>{
    this.message$.next(message);
    const reciverID = this.socket.id;
    console.log('Receiver ID = ', reciverID)
   });

   return this.message$.asObservable();
   };
   }

这是我的 angular 打字稿文件

   import { Component } from '@angular/core';
   import { ChatService } from './chat.service';

   export interface MessageModel{
   message?: string;
   senderId?:string; 
  }

  @Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
  })
  export class AppComponent {
   public socketId: string = '';
   constructor(private chatService: ChatService){}

   newMessage!: string;
   messageList: MessageModel[] = [];

   ngOnInit(){
    this.socketId = this.chatService.socketID;
    console.log('this.socketID',  this.socketId)
    this.chatService.getNewMessage().subscribe((message: MessageModel) => {
    const socketId = message.senderId;
    console.log('Sockit ID = ',socketId);
    this.messageList.push(message);
  
   });
   }
   sendMessage() {
    this.chatService.sendMessage(this.newMessage);
    this.newMessage = '';
   }
  }

这是我的 html 文件,用于显示消息

   <div class="chats" *ngFor="let message of messageList">
    <div *ngIf="message">
      <div   *ngIf="socketId === message.senderId" class="client-chat"> 
        {{message.message}}
      </div>
      <div    *ngIf="socketId !== message.senderId"  class="my-chat"> 
        {{message.message}}
      </div>
    </div>
  </div>

这是我的 css 样式,通过样式将发件人消息与接收者分开

 .client-chat{
   width: 60%;
   word-wrap: break-word;
   background-color: #4f5d73c7;
   padding: 7px 10px;
   border-radius: 10px 10px 10px 0px;
   margin: 10px 0px;
 }
 .my-chat{
   width: 60%;
   word-wrap: break-word;
   background-color: #77b3d4c7;
   padding: 7px 10px;
   border-radius: 10px 10px 0px 10px;
   margin: 5px 0px 5px auto;
  }

这是发送方结果

这是接收方的结果

我无法创建分离消息发送者和接收者的逻辑,请任何人解决我的问题在此先感谢

您从未在 ChatService

中更新过 socketID
this.socket.on('myId', (id)=>{
    console.log('from service',id);
    this.socketID = id;   //missing this line
});

编辑:

当你更新ChatService中的socketID时,AppComponent中的socketId不会更新,因为你只在[=20中设置了一次socketId =].

你能做的最简单的事情就是完全摆脱 socketId 字段,使 chatService public 并直接在你的 [=33= 中访问 chatService.socketID ]模板。

export class AppComponent {
   //public socketId: string = '';
   constructor(public chatService: ChatService){}

   //...
}

<div class="chats" *ngFor="let message of messageList">
    <div *ngIf="message">
        <div   *ngIf="chatService.socketID === message.senderId" class="client-chat"> 
            {{message.message}}
        </div>
        <div    *ngIf="chatService.socketID !== message.senderId"  class="my-chat"> 
            {{message.message}}
        </div>
    </div>
</div>