node.js - 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 实现套接字。
解决方案
推荐阅读
- python - 在python中查找重叠的时间段
- sql - 你可以让一个主键引用另一个表中的另一个主键吗?如果是这样,在什么情况下会使用它?
- node.js - 当我为 prod 构建时,我得到散列文件,当用户刷新时,我们得到 404 个文件,不知道如何修复它
- javascript - 有没有办法让您的 JQuery 验证填充到文档中?
- html - Bootstrap 网格柱没有对齐角落到角落
- python - 尝试通过使用 if 语句过滤另一列来在 pandas 数据框中创建一个新列
- python - 在for循环中将numpy矩阵写入csv文件
- javascript - 如何将函数作为属性传递给 React 组件?
- apache-spark - 如何在 Azure Databricks 中的 spark 工作人员上部署 jar 依赖项(本机 dll)?
- python - 使用 Python tesseract 从 PNG 图像中提取文本