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

Time:11-09

All things working well but problem is that i want to show sender and receiver message on different side but i don't know how i can implement this i also getting socket ids from server side but i'm not able to create logic how i can differentiate sender and receiver message on my html page please anyone can help me Thanks in advance

this is my server side code

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

this is my chatserivce file from agular side

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

This is my angular typescript file

   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 = '';
   }
  }

this is my html file for displaying messages

   <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>

This is my css style to seprate sender message to receiver through styling

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

this is sender side result enter image description here

this is receiver side result enter image description here

i am not able to create logic for sepeerating message sender and receiver please anyone can solve my problem Thanks in advance

CodePudding user response:

You have never updated socketID in ChatService

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

Edit:

When you update socketID in ChatService, the socketId in AppComponent is not updated, because you only set socketId once in ngOnInit.

The simplest thing you can do is to completely get rid of the socketId field, make chatService public and access chatService.socketID directly in your HTML template.

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>
  • Related