Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
simonaco Avatar asked May 07 '16 14:05

simonaco


People also ask

Can I use Socket.IO in angular?

After creating the Angular app, we need to install the Socket. IO-Client package which will help us communicate between our front-end and our server.

How do I import Socket.IO into typescript?

import * as express from 'express'; import * as http from 'http'; import * as socketIo from 'socket.io'; const app: express. Express = express(); const httpServer: http. Server = new http. Server(app); const io: any = socketIo(); const port: string | number = process.


2 Answers

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.

like image 98
Abdulrahman Alsoghayer Avatar answered Oct 03 '22 06:10

Abdulrahman Alsoghayer


This is a late answer since I just had this problem and installing correct types via npm solved it for me:

npm install @types/socket.io-client --save

This package contains type definitions for socket.io-client, so if you are getting type errors this should fix it.

like image 22
Lucas Avatar answered Oct 03 '22 06:10

Lucas