Ntlzz93 Ntlzz93 - 7 days ago 5
AngularJS Question

How to create a function connect socket io in factory angular js?

I'm creating a factory's socket in angular js, however

on
&
emit
function as out of connection's localhost:5793. I mean
var socket = io.connect();
&
socket = io.connect('http://localhost:5793');
are 2 diffirent connection. Do right?. How to 2 socket io are the same variable ( connection )?

var App = angular.module("App", [

]);

App.factory('socket', ['$rootScope', function($rootScope) {
var socket = io.connect();
return {
connect: function() {
socket = io.connect('http://localhost:5793');
},
on: function(eventName, callback) {
socket.on(eventName, callback);
},
emit: function(eventName, data) {
socket.emit(eventName, data);
}
};
}]);

Answer

With this line, you create new socket connection - although I'm not entirely sure since you didn't pass any URL

var socket = io.connect();

then with the following code, you overwrite the variable socketand lose the reference to the previously open socket

connect: function() {
    socket = io.connect('http://localhost:5793');
},

so bottom line the variable socket holds reference to only one connection not two

Comments