In my project, I will create a private conversation system between users with SignalR using Angular and ASP.NET Core. SignalR connection is successful and message sending is successful. However, the message is not delivered to the user to whom I sent the message. What could be the reason?
I want messages to be sent only between two users by id and not to a group.
This is my ChatHub class which is in the server side
using Microsoft.AspNetCore.SignalR;
namespace FineMaster.Server.Hubs
{
public class ChatHub : Hub
{
public async Task SendPrivateMessage(int senderId, int receiverId, string message)
{
await Clients.Client(receiverId.ToString()).SendAsync("ReceiveMessage", senderId, message);
}
}
}
And this is my service.ts
file which is on the client side
import { Injectable } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ChatService {
private hubConnection: HubConnection;
private message$: Subject<any> = new Subject();
constructor() {
this.hubConnection = new HubConnectionBuilder()
.withUrl('https://localhost:7235/chat')
.build();
}
async startConnection(): Promise<void> {
try {
await this.hubConnection.start();
console.log('SignalR connected!');
} catch (error) {
console.error('Error connecting to SignalR:', error);
}
}
sendMessage(senderId: number, receiverId: number, message: string): Promise<boolean> {
return this.hubConnection.invoke('SendPrivateMessage', senderId, receiverId, message)
.then(() => {
console.log(senderId + 'says ' + message + " to " + receiverId);
return true; // Indicate successful message sending
})
.catch(error => {
console.error('Error sending message:', error);
return false; // Indicate error during message sending
});
}
onReceiveMessage(): Observable<string> {
this.hubConnection.on("ReceiveMessage", (messages) => {
this.message$.next(messages);
});
return this.message$.asObservable();
}
}
and this is component page where i want to get message
ngOnInit(): void {
const storedUser = this.cookieService.get("userInfo");
if (storedUser) {
var storedUserJson = JSON.parse(storedUser);
this.currentUserID = storedUserJson.id;
}
this.chatService.startConnection();
this.chatService.onReceiveMessage().subscribe(response => {
console.log("bişey geldi: ", response);
});
}
in console the receiver id sender id and message is true