Skip to content

Commit fcb61f0

Browse files
setuppati i messaggi
1 parent c29cad1 commit fcb61f0

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

src/app/api/services/websocket.service.ts

+15-6
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,20 @@ export class WebSocketService implements OnDestroy {
1111
private stompClient: Client;
1212
private messagesSubject = new BehaviorSubject<any[]>([]);
1313
public messages$: Observable<any[]> = this.messagesSubject.asObservable();
14+
private connectionSubject = new BehaviorSubject<boolean>(false);
15+
public connection$: Observable<boolean> =
16+
this.connectionSubject.asObservable();
1417

1518
constructor(private http: HttpClient) {
16-
const socket = new SockJS("http://localhost:8080/ws");
19+
const socket = new SockJS("http://localhost:8080/chat-socket");
1720
this.stompClient = new Client({
1821
webSocketFactory: () => socket as WebSocket,
1922
reconnectDelay: 5000,
2023
});
2124

2225
this.stompClient.onConnect = () => {
23-
this.stompClient.subscribe("/user/queue/messages", (message: Message) => {
26+
this.connectionSubject.next(true);
27+
this.stompClient.subscribe("/chat/queue/messages", (message: Message) => {
2428
this.messagesSubject.next([
2529
...this.messagesSubject.value,
2630
JSON.parse(message.body),
@@ -30,16 +34,21 @@ export class WebSocketService implements OnDestroy {
3034

3135
this.stompClient.onStompError = (error) => {
3236
console.error("WebSocket connection error", error);
37+
this.connectionSubject.next(false);
3338
};
3439

3540
this.stompClient.activate();
3641
}
3742

3843
sendMessage(message: any): void {
39-
this.stompClient.publish({
40-
destination: "/app/chat",
41-
body: JSON.stringify(message),
42-
});
44+
if (this.connectionSubject.value) {
45+
this.stompClient.publish({
46+
destination: "/app/chat",
47+
body: JSON.stringify(message),
48+
});
49+
} else {
50+
console.error("WebSocket connection is not established");
51+
}
4352
}
4453

4554
loadMessages(conversationId: number): void {

src/app/message/message.component.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ export class MessageComponent implements OnInit, OnDestroy {
3030
this.recipientId = params["destId"];
3131
this.userId = params["userId"];
3232
});
33-
console.log(this.userId, this.recipientId);
3433
}
3534

3635
async ngOnInit() {
@@ -52,6 +51,7 @@ export class MessageComponent implements OnInit, OnDestroy {
5251
const message = {
5352
text: this.newMessage,
5453
recipient: { id: this.recipientId },
54+
sender: { id: this.userId },
5555
};
5656
this.webSocketService.sendMessage(message);
5757
this.newMessage = "";

0 commit comments

Comments
 (0)