【发布时间】:2022-03-05 03:32:02
【问题描述】:
我正在使用 Angular 和 NestJS 以及 socket.io 来创建一个聊天应用程序。
当我开始在我的数据库上保存数据时,我的 Angular 端停止更新消息,除非页面刷新。
我找不到在服务器网关上传递userid 以便在数据库中搜索用户聊天的方法。
角度服务
sendMessage(chat: Chat): void {
this.socket.emit('sendMessage', chat)
} //using it when a message is sent
getNewMessage(): Observable<Chat[]> {
return this.socket.fromEvent<any>('lastChats');
} //using it onInit
sendId(userId: number): void {
this.socket.emit('loadMessages', userId);
} //using it onInit
NestJS 网关
@WebSocketGateway({ cors: { origin: ['http://localhost:4200'] } })
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
constructor(
@InjectRepository(Chat) private chatRepository: Repository<Chat>,
) { }
@WebSocketServer()
server: Server
async handleConnection(client: any, ...args: any[]) {
const chats = await this.chatRepository.createQueryBuilder('chat')
.innerJoinAndSelect('chat.ally', 'ally')
.innerJoinAndSelect('chat.talent', 'talent')
.getMany();
this.server.emit('lastChats', chats)
}
handleDisconnect(client: any, ...args: any[]) {
console.log("Disconnected")
}
@SubscribeMessage('sendMessage')
handleMessage(socket: Socket, chat: Chat) {
if (chat.messagesJSON && chat.messagesJSON.trim() !== '') {
this.chatRepository.save(chat)
this.server.emit('newChat', chat)
}
@SubscribeMessage('loadMessages')
async handleLoad(socket: Socket, id: number) {
const chats = await this.chatRepository.createQueryBuilder('chat')
.innerJoinAndSelect('chat.ally', 'ally')
.innerJoinAndSelect('chat.talent', 'talent')
.where('ally = :user OR talent = :user', { user: id })
.getMany();
this.server.emit('lastChats', chats)
}
}
【问题讨论】:
标签: node.js angular sockets socket.io nestjs