gpt4 book ai didi

javascript - Socket.io 发射两次火焰

转载 作者:太空宇宙 更新时间:2023-11-03 22:31:33 25 4
gpt4 key购买 nike

我在 Node.js 后端设置了一个 socket.io,它会发出某些事件,然后 AngularJS 捕获并显示错误并更改一些 $rootScope 变量。我有一个问题,这个发射似乎每次都会触发两次,给我两个通知,但我不知道问题出在哪里

server.js(缩写)

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);
});
});

最佳答案

好吧,答案是将 AngularJS socket.on() 移至服务而不是 Controller 。 Controller 被调用两次,导致重复触发。

关于javascript - Socket.io 发射两次火焰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36540212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com