我正在尝试将通过初始化socket.io得到的io对象导出到打字稿中的路由器模块,我是从server.ts模块导出io对象还是在路由器模块中初始化socket.io?还是其他建议的方式?
我尝试过
Server.ts
export const io = socketIO.listen(server);
customer-router.ts
console.log(io)
计算为未定义。
Server.ts
import {Server, createServer} from 'http';
// Init express
const app = express();
// Setup socket.io
const server: Server = createServer(app);
export const io = socketIO.listen(server);
export default server;
Start.ts
import { logger } from '@shared';
// Start the server
const port = Number(process.env.PORT || 3000);
server.listen(port, () => {
logger.info('Express server started on port: ' + port);
});
BaseRouter.ts
import CustomerRouter from './customers/Customers';
const router = Router();
const path = '/ChowApi';
// Add sub-routes
router.use(CustomerRouter.path, CustomerRouter.router);
// Export the base-router
export default { router, path };
Customer.ts
console.log(io)
export default { router, path };
我希望输出是io对象, 但是实际输出是不确定的
答案 0 :(得分:0)
有人帮助我解决了这个问题,以防万一有人碰到这个问题。
// server.ts
import * as socketIO from 'socket.io';
import BaseRouter from './routes/Base';
const server = createServer(app);
const io = socketIO.listen(server);
const baseRouter = BaseRouter(io);
app.use(baseRouter.path, baseRouter.router)
// BaseRouter.ts
import { Router } from 'express';
export const BaseRouter = (io) => {
// Init router and path
const router = Router();
const path = '/ChowApi';
// Add sub-routes
const customerRouter = CustomerRouter(io);
router.use(customerRouter.path, customerRouter.router);
return {
router,
path
};
}
export default BaseRouter;
// Customer.ts
const CustomerRouter = (io) => {
// Init router and path
const router = Router();
const path = '/customers';
return {
router,
path
}
};
export default CustomerRouter;
我不知道为什么我没有想到这一点。