simonaco simonaco - 6 months ago 1252
Javascript Question

How to import socket.io-client in a angular 2 application?

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


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

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


In my component, I am importing sockets.io:

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


And then using it:

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


This fails with:

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


Any ideas?

Answer

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

And change your import to:

import io from 'socket.io-client';
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>

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

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

Comments