如何在 angular 2 应用程序中导入 socket.io-client? [英] How to import socket.io-client in a angular 2 application?

查看:38
本文介绍了如何在 angular 2 应用程序中导入 socket.io-client?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 angular 2 应用程序中包含 sockets.io-client.首先我安装了socket.io-client,安装了typings:

I want to include sockets.io-client in my angular 2 application. First I installed socket.io-client, installed typings:

npm install socket.io-client --save
typings install socket.io-client --save --ambient

下一步是将 socket.io-client 包含到我的 index.html 中:

Next step was to include socket.io-client into my index.html:

 <script src="node_modules/socket.io-client/socket.io.js"></script>

在我的组件中,我正在导入 sockets.io:

In my component, I am importing sockets.io:

import * as io from 'socket.io-client'

然后使用它:

var socket = io('http://localhost:3000');
socket.on('event', function(data:any){
   console.log(data);
}.bind(this)); 

这失败了:

zone.js:101 GET http://localhost:3001/socket.io-client 404 (Not Found)
(index):18 Error: Error: XHR error (404 Not Found) loading http://localhost:3001/socket.io-client

有什么想法吗?

推荐答案

为了注册模块以便您可以导入它,您需要将它包含在您的 SystemJS 配置中.

In order to register the module so you can import it, you need to include it in you SystemJS configuration.

System.config({
    packages: {
        ...
        "socket.io-client": {"defaultExtension": "js"}
    },
    map: {
        "socket.io-client": "node_modules/socket.io-client/socket.io.js"
    }
});

并将您的导入更改为:

从'socket.io-client'导入io;
import * as io from "socket.io-client

此外,您不再需要在 script 标签中导入,因此请删除:

Also, you don't need the import in the script tag anymore, so remove:

<script src="node_modules/socket.io-client/socket.io.js"></script>

最后,如果您想添加类型,请在您的 typings.json 中添加:

Finally, if you like to add the typings, add in your typings.json:

{
  "ambientDependencies": {
    ...
    "socket-io-client":"github:DefinitelyTyped/DefinitelyTyped/socket.io-client/socket.io-client.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd"
  }
}

附言Int 将来,将typings 中的hash 更改为最新的commit hash.

P.S. Int the future, change the hash in the typings to the latest commit hash.

这篇关于如何在 angular 2 应用程序中导入 socket.io-client?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆