我正在将socket.io
与nodejs
一起使用,并尝试通过该类的方法之一获取socketio
实例。
项目文件夹结构:
我有以下代码:
app.ts
:
class App {
public app: express.Application;
private PORT: number;
private dbUrl = DB_URL as string;
public IO = null;
constructor(routes: any, port: any) {
this.app = express();
this.config();
}
public listen = (): void => {
const server = this.app.listen(this.PORT, () => {
console.log(`Server is running on port ${this.PORT}`);
});
const io = socket(server);
this.IO = io; <-- IO
};
}
export default App;
server.ts
import App from "./app";
import Auth from "./Route/Auth";
import TwitterFeed from './Route/TwitterFeed';
import EconomicFeed from './Route/EconomicFeed';
require("dotenv").config();
const { PORT } = process.env;
const app = new App([new Auth(), new TwitterFeed(), new EconomicFeed()], PORT);
app.listen();
export default app; <-- export app here
TwitterFeed
:
import app from '../../server';
class TwitterFeed {
.
.
.
private streamPublicTweets = (request:Request, response:Response)=>{
// establish socket connection
console.log('app', app.IO); <-- this is displayed with no error
const io = app.IO
io.on('connection', (socket: any) => {
console.log('socket connected');
streamTweets(this.T, socket)
});
}
}
在TwitterFeed
类中,我尝试使用一种方法访问app
导入。
在控制台中,没有错误的输出:
我在这里想念什么?