Warning: I'm pretty new to coding and web development.
I am creating an angular application that uses socket.io to exchange real-time events on a node (express) server with other clients. The problem I am facing is that when I am in the application and switch routes from "/ pb" to "/" and then again, the socket event "init" is fired twice on the client side. From what I can tell, the client fires the requestInit event only once, and the server responds by raising the init event only once. However, the client runs the code in socketio.on ('init') function several times when I switch views.
For example: I will open the application and go to / pb, the console will write
connected to socket
recieved socket event from server: Init
initCount: 1
Now when I go to "/" and then back to "/ pb", the console will write
recieved socket event from server: Init
initCount: 2
recieved socket event from server: Init
initCount: 1
Each time I switch views, initCount gets higher, so if I switch back and forth 5 times, initCount will record 5 times, starting at 5 and ending at 1.
socketio.on('init') , . , , , , , "init" . socketio.on('connect') "/pb" . , , . . , .
:
var app = angular.module('MainApp', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider){
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController',
activeTab: 'home'
})
.when('/pb', {
templateUrl: 'views/pb.html',
controller: 'PbController',
activeTab: 'pb'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
app.factory('socketio', ['$rootScope', function($rootScope){
var socket = io.connect('http://localhost:3000');
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);
}
});
});
}
};
}]);
app.controller('PbController', ['$scope', 'socketio', function ($scope, socketio){
$scope.initCount = 0;
socketio.emit('requestInit');
socketio.on('connect', function(){
console.log('connected to socket');
});
socketio.on('init', function (){
console.log("recieved socket event from server: Init");
$scope.initCount += 1;
console.log("init count: " + $scope.initCount);
});
}]);
:
var pbServerController = function (io){
io.on('connection', function (socket){
console.log("Client connected, new socket issued: "+socket.id);
socket.on('requestInit', function(){
console.log("sending Init socketio event");
socket.emit('init');
});
};
module.exports = pbServerController;