io.on 使用 socket.io、node 和 angular 返回 undefined

io.on returns undefined, using socket.io, node and angular

提问人:Leonardo Mestre 提问时间:2/10/2023 最后编辑:Leonardo Mestre 更新时间:2/10/2023 访问量:90

问:

我在使用 socket.io 时遇到了问题,当我执行 io.on 时,它没有传递参数。当参数到达客户端时,它是未定义的。

在节点中,当我发送 io.to().emit(“number”, JSON.parse('{“number”:“1”}')) 传递的值是未定义的,即使传递的是设定值 服务器节点:${room}

    const express = require('express');
    const app = express();
    const http = require('http');
    const server = http.createServer(app);
    const cors = require('cors');


    const io = require('socket.io')(server, {
      cors: {
        origin: '*',
      }
    });


    users = []

    app.get('/', (req, res) => {
      res.send('<h1>Hello world</h1>');
    });

    server.listen(3000, () => {
  

      console.log('listening on *:3000');

      io.on('connection', (socket) => {
          console.log('a user connected');
  
          socket.on('conexao', (data)=>{
            console.log(data)
          })
      
          socket.on('joinRoom', data=>{
            console.log(data)
            const userInRoom = users.find(user=> user.username === data.name && user.room ===     data.room)
            if(userInRoom){
              userInRoom.socketId = socket.id
            }else{
              users.push({
                socketId: socket.id,
                username: data.name,
                room: data.room
              })
            }
            socket.join(data.room) 
            console.log("sala criada")
          })

          socket.on("room", (room)=>{
            io.to(`${room}`).emit("number", JSON.parse('{"number":"1"}'))
          })
  
          socket.on('disconnect', () => {
            console.log('user disconnected');
          });
        });
        io.attach(server)

    });

```

 here I am passing a number informing what the room is and I want to receive a parameter to test if the room is working. to get to this page the user has already entered the room angular typescript that makes the call:

```
    import { SocketService } from './../../services/socket.service';
    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-room',
      templateUrl: './room.component.html',
      styleUrls: ['./room.component.scss']
    })
    export class RoomComponent implements OnInit {
      roomNumber:string = ''
      constructor(private socket:SocketService){
    
      }

      ngOnInit(): void {
        this.socket.on('number', (numero:JSON) =>{
          console.log(numero)
          const obj = JSON.parse(numero.toString())
          console.log("test")
          this.roomNumber = obj.number
        })
    
      }

      emit(){
        this.socket.emit('room', 123456 )
      }
  
    }

```
appmodule:


```
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
    import { HeaderComponent } from './templates/header/header.component';
    import { FooterComponent } from './templates/footer/footer.component';
    import { HomeComponent } from './components/home/home.component';
    import { RulesComponent } from './components/rules/rules.component';
    import { RoomComponent } from './components/room/room.component';

    const config: SocketIoConfig = {url:'http://localhost:3000'}

    @NgModule({
      declarations: [
        AppComponent,
        HeaderComponent,
        FooterComponent,
        HomeComponent,
        RulesComponent,
        RoomComponent
      ],
       imports: [
        BrowserModule,
        AppRoutingModule,
        SocketIoModule.forRoot(config)
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
```

    The code is simple because I'm just testing the communication to continue the project.

    erro: ERROR TypeError: Cannot read properties of undefined (reading 'toString')
        at room.component.ts:18:37
        at SocketService.on (socket.service.ts:16:31)
        at RoomComponent.ngOnInit (room.component.ts:16:17)
        at callHook (core.mjs:2488:22)
        at callHooks (core.mjs:2457:17)
        at executeInitAndCheckHooks (core.mjs:2408:9)
        at refreshView (core.mjs:10434:21)
        at refreshEmbeddedViews (core.mjs:11434:17)
        at refreshView (core.mjs:10443:9)
        at refreshComponent (core.mjs:11480:13)






I'm sending a call to the socket passing the room number and it should pass me a number back. instead it passes undefined. I've tried passing number, string and JSON and nothing worked. detail that the room is being created, as the error only happens if I am in the room "123456"
node.js angularjs websocket socket.io

评论


答: 暂无答案