Sommereder
Sommereder

Reputation: 924

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

Hej there.

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 - wich 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.

Upvotes: 0

Views: 2435

Answers (3)

Sommereder
Sommereder

Reputation: 924

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.

Upvotes: 1

Thierry Templier
Thierry Templier

Reputation: 202196

You need to install the socket.io typings (see this link: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/socket.io/socket.io.d.ts) using the command:

$ tsd install socket.io

Then you need import it:

import * as io from 'socket.io';

Upvotes: 0

dvlsg
dvlsg

Reputation: 5538

I would note that if you're using electron that you shouldn't really consider electron.js to be server side. It's more of a client launcher / bootstrap, and must be running on each client. You'd have to have a separate node application (and I would strongly suggest it, in the case of socket.io) to truly make your code server side.

As for your question, you could try adding import io from 'socket.io-client' or var io = require('socket.io-client') in your root component (after you npm install socket.io-client, if necessary).

Upvotes: 0

Related Questions