首页 > 解决方案 > NodeJS 中带有 fromEvent 可观察对象和 Typescript 的 Socket.io

问题描述

我想用 RxJs 绑定套接字事件。我是 RxJs 的新手。我正在使用带有 NodeJs 的打字稿。我尝试在一些博客之后使用 RxJs 实现 Socket.io,但遇到类型问题,显示错误 socket.Server 不可分配给 FromEventTarget<{}>。

.Rxjs 6.3.3、节点 10.14.2、Socket-io 2.2.0、Typescript 2.9.2、Express 4.16.4

 import * as socketio from "socket.io";
 import { of, fromEvent } from 'rxjs';
 import { switchMap, map, mergeMap, takeUntil, tap } from 'rxjs/operators';

  class SocketServer {
    createSocketServer(http) {
    const io$ = of(socketio(http));
            const connection$ = io$.pipe(
        switchMap((io) => {
            return fromEvent(io, 'connection').pipe( 
    // ====> this line io giving error Argument of type 'Server' is not assignable to parameter of type 'FromEventTarget<{}>'.
    // ==> Property 'off' is missing in type 'Server' but required in type 'JQueryStyleEventEmitter'.ts(2345)
                tap(res => console.log('socket conected success fully', res)),
                map(client => ({ io, client }))
            )
        })
    );
    // Stream of disconnections
    const disconnect$ = connection$.pipe(
        mergeMap(({ client }) => {
            return fromEvent(client, 'disconnect').pipe(  
    // <===== in this line showing error type client: {} not assignable to FromEventTarget<{}>
                map(() => client)
            )
        })
    );
    // On connection, listen for event
    const listen = (event) => {
        return connection$.pipe(
            mergeMap(({ io, client }) => {
                return fromEvent(client, event).pipe(
                    takeUntil(disconnect$),
                    map(data => ({ io, client, data }))
                )
            })
        )
    }
     }

 }

寻找这种模式的最佳解决方案,以使用带有 Typescript 和节点的 RxJs 实现套接字。

标签: node.jstypescriptexpresssocket.iorxjs6

解决方案


推荐阅读