yaboiduke yaboiduke - 2 months ago 25
Javascript Question

Return value from Socket.io function in Angular factory

I have a sockets factory defined to return an array that is coming from my server in the

data
argument of
socket.on('user_entrance')
.

.factory('sockets',function(){

var user_name = window.prompt('enter your name');

var socket = io('http://localhost:3002');

var online_users = [];

socket.emit('user_name', user_name);
socket.on('user_entrance', function(data,my_id){

online_users.push(data);

});

return online_users;

})


and in the controller I want to use the
online_users
, I inject the dependency on the "sockets factory" like so,but returns undefined.

.controller('ChatsCtrl', function($scope, Chats,sockets) {


//this is undefined
console.log(online_users);


})


However whats strange is if I run this code in any controller it works fine.

.controller('someCtrl',function(){

var user_name = window.prompt('enter your name');

var socket = io('http://localhost:3002');

var online_users = [];

socket.emit('user_name', user_name);
socket.on('user_entrance', function(data,my_id){

online_users.push(data);

});


//this works fine
console.log(online_users);

})


I would like to run the code in a factory so I can access the returned values in other controllers.How can I get this to work?

Answer

When you inject the factory, you have to reference it by the name of the parameter it is injected into:

.controller('ChatsCtrl', function($scope, Chats,sockets) {
   console.log(sockets);
})