[英]Socket.io emit fires twice
I have set up a socket.io on my Node.js back end which emits certain events that AngularJS then captures and shows errors and changes some $rootScope variables. 我在Node.js后端设置了一个socket.io,它发出某些事件,AngularJS然后捕获并显示错误并更改某些$ rootScope变量。 I have a problem where this emit seem to fire twice every time giving me two notifications and I don't know where the problem is 我有一个问题,似乎每次发出两次通知时都会发射两次,我不知道问题出在哪里
server.js (shortened)
var socket = require('socket.io');
var app = express();
var router = express.Router();
app.use('/api', router);
var server = app.listen(config.conn_port, function(){
console.log("Server launched at port " + config.conn_port);
});
var io = socket.listen(server);
require('./api/routes')(router, connection, io);
routes.js
module.exports = function(router, connection, socket) {
# Net event
client.on('error', function () {
socket.emit('serverDisconnected', {message: 'Connection ended', server_conn: false});
});
}
app.js (AngularJS)
app.factory('socket', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
AngularJS Controller
dashboardModule.controller('dashboardMain', function ($scope, $http, $rootScope, Notification, socket) {
socket.on('serverDisconnected', function (message) {
Notification.error(message.message);
});
});
Well, the answer was to move the AngularJS socket.on() to a service instead of a controller. 好吧,答案是将AngularJS socket.on()移至服务而不是控制器。 The controller gets called twice which causes the duplicate firing. 控制器被调用两次,导致重复触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.