In my current project, I am working on a chat application using Angular with WebSocket integration. Let me provide an overview of the architecture I have designed for this project. I created a module called 'chatting' which contains a list of users. When I select a user from this list, another component named 'message' opens up.
Now, my goal is to send the user's id along with the message to the backend using a service. The user's id is obtained from the URL parameter using this.route.snapshot.params['id'] in the message.ts file.
My question: How can I pass this id to the service.ts file?
Note: I have attempted to implement this functionality using various WebSocket methods but it has not been successful.
------ My Attempt ------
message.component.ts
this.idUser = this.route.snapshot.params['id'];
sendMessage(event: any, avatar: string, idUser:Number) {
let obj: Message = {
text: event.message,
avatar: avatar,
username: this.username,
idUser: this.idUser
} ;
console.log("id set in message:", obj.idUser)
this.chatService.sendMessage(obj);
}
service.ts
idUser: Number = 0;
initializeWebSocketConnection() {
const serverUrl = 'http://localhost:8020/chat-websocket/' + this.idUser;
console.log("id in service:", serverUrl)
const ws = new SockJS(serverUrl);
this.stompClient = Stomp.over(ws);
const that = this;
this.stompClient.connect({}, function(frame: any) {
let message: any;
that.stompClient.subscribe('/chat/messages', function (message: any) {
if (message.body) {
const obj = JSON.parse(message.body);
that.addMessage(obj.text, obj.username, obj.avatar, obj.idUser);
}
});
});
}
addMessage(message: any, username: string, avatar: string, idUser: Number) {
this.messages.push({
text: message,
date: new Date(),
user: {
name: username,
avatar: avatar,
idUser: idUser
}
});
}
// Send a chat message using stomp client
sendMessage(msg: Message) {
this.stompClient.send('/app/sendmsg', {}, JSON.stringify(msg));
}}
interface IMessage {
text: string;
date: Date;
user: IUser;
}
interface IUser {
idUser: Number;
name: string;
avatar: string;
}