【问题标题】:ngx-socket-io - Can not receive and send eventsngx-socket-io - 无法接收和发送事件
【发布时间】:2024-01-22 06:23:01
【问题描述】:

我已经在我的应用程序中实现了socket-io 服务器,并且我正在使用ngx-socket-io 我的Angular 应用程序与该服务器通信。

我的服务器实现:

const io = socketio(server);

io.on('connection', socket => {
    console.log('connection!')
    socket.emit('notification');
});

连接我的应用后,connection!消息打印成功,表示客户端成功链接到WS服务器。

但是我的notification 事件监听器没有收到任何事件...

我的WebSocketService

import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';

@Injectable()
export class WebSocketService {
    constructor(
        private socket: Socket,
    ) {}

    public getEventListener() {
        return this.socket.fromEvent('notification');
    }
}

订阅(在其他服务中):

@Injectable()
export class NotificationService {
    ...

    constructor(
        private wsService: WebSocketService,
    ) {
        console.log('Test')
        this.wsService.getEventListener().subscribe(() => console.log(123));
    }

    ...
}

Test 已打印,但 123 未打印。

【问题讨论】:

    标签: node.js angular websocket


    【解决方案1】:

    我的服务器配置无效。我将我的服务器 URL 放在 /api 路由中,而不是主路由。

    应用模块导入:

    SocketIoModule.forRoot({ url: 'http://localhost:3000/api' }),
    

    固定:

    SocketIoModule.forRoot({ url: 'http://localhost:3000' }),
    

    【讨论】: