[英]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')
. 我有一个套接字工厂定义为在
socket.on('user_entrance')
的data
参数中返回一个来自服务器的数组。
.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. 在控制器中我想使用
online_users
,我像这样注入对“ sockets factory”的依赖,但是返回未定义。
.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);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.