【问题标题】:angular-nestjs socket.io doesn't update if page doesn't refresh如果页面不刷新,angular-nestjs socket.io 不会更新
【发布时间】: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


    【解决方案1】:
    To send from angular to nestjs you can use
    
    Angular:
    
    this.socket = io(environment.SOCKET_URL, {
          extraHeaders: {Authorization: localStorage.getItem('token')},
        });
    
    
    Nestjs: in the handleConnexion
    
        Const jwt =socket.handshake.headers.authorization
    
    I think you can replace the token by usrerId 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 2011-05-07
      • 1970-01-01
      相关资源
      最近更新 更多