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?
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);
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.