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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With