javascriptnode.jswebsocketsocket.ioangular

Can't connect to my WebSocket from within my Angular2 app


I have a app using Node.js/Electron/Angular2 (TypeScript). Using socket.io I created a WebSocket. Everything works fine, as long as I'm not inside my Angular2 app.

I tried the whole day to get this running, without luck. I downloaded a working tutorial, but can't find the missing link. Drives me crazy!

The error - which does not stop the compilation - I get, is root.component.ts(14,17): error TS2304: Cannot find name 'io'..

How can I get rid of that error? Or better: What's the best practice for this websocket communication inside Angular2?

Thanks in advance.


Solution

  • Now I solved this issue this way:

    1. Installed socket.io-client typings $ tsd install socket.io-client and
    2. added a typings reference to my main.ts file ///<reference path="../../typings/socket.io-client/socket.io-client.d.ts"/>.
    3. Installed socket.io-client Node.js module $ npm install --save socket.io-client and
    4. added this module to my index.html <script src="../node_modules/socket.io-client/socket.io.js"></script>

    Now I can simply work with the socket inside any Angular2 component, without adding any extra lines.

    socket = null;
    
    constructor() {
        this.socket = io('http://localhost:8181');
        this.socket.on('news', function (data) {
            console.log(data);
        });
    }
    

    And for reference, this is my server socket code inside my main Electron .js file:

    var server = require('http').createServer(function(req, res) {})
        socket = require('socket.io')(server, {});
    
    server.listen(8181);
    
    socket.on('connection', function(socket) {
        socket.emit('news', {hello: 'world'});
        socket.on('my other event', function(data) {
            console.log(data);
        });
    });
    

    Hope this helps anyone later. Thank to Thierry Templier and dvlsg for the help.