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

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

问题描述

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

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

此外,您不再需要在脚本标记中导入,因此请删除:

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"
  }
}

PS Int将来,将打字中的散列更改为最新的提交散列。

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

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

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