gpt4 book ai didi

javascript - 无法从我的 Angular2 应用程序中连接到我的 WebSocket

转载 作者:行者123 更新时间:2023-12-03 07:25:00 25 4
gpt4 key购买 nike

嘿嘿。

我有一个使用 Node.js/Electron/Angular2 (TypeScript) 的应用程序。我使用 socket.io 创建了一个 WebSocket。只要我不在我的 Angular2 应用程序中,一切都会正常工作。

我一整天都在尝试让它运行,但没有运气。我下载了一个工作教程,但找不到丢失的链接。让我发疯!

  • 这是我的electron.js启动应用程序,创建 websocket 服务器端
  • 这是我的index.html使用可用的 websocket,但作为 native JavaScript 代码
  • 这是我的root component Angular2 尝试让 websocket 运行

错误 - 不会停止编译 - 我得到的是 root.component.ts(14,17): error TS2304: Cannot find name 'io'..

如何消除该错误?或者更好:Angular2 内部的 websocket 通信的最佳实践是什么?

提前致谢。

最佳答案

现在我这样解决了这个问题:

  1. 已安装 socket.io-client 类型 $ tsd install socket.io-client
  2. 向我的 main.ts 文件添加了打字引用 ///<reference path="../../typings/socket.io-client/socket.io-client.d.ts"/> .
  3. 已安装 socket.io-client Node.js 模块 $ npm install --save socket.io-client
  4. 将此模块添加到我的index.html <script src="../node_modules/socket.io-client/socket.io.js"></script>

现在我可以简单地使用任何 Angular2 组件内的套接字,而无需添加任何额外的行。

socket = null;

constructor() {
this.socket = io('http://localhost:8181');
this.socket.on('news', function (data) {
console.log(data);
});
}

作为引用,这是我的主 Electron .js 文件中的服务器套接字代码:

var server = require('http').createServer(function(req, res) {})
socket = require('socket.io')(server, {});

server.listen(8181);

socket.on('connection', function(socket) {
socket.emit('news', {hello: 'world'});
socket.on('my other event', function(data) {
console.log(data);
});
});

希望这对以后的人有帮助。感谢 Thierry Templier 和 dvlsg 的帮助。

关于javascript - 无法从我的 Angular2 应用程序中连接到我的 WebSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36041019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com