I want to use socket.io only at one section of my webapp. I use socket.io's set('authorization', fn) for handshaking the current context(express session and page-id). This works great when I refresh the current page, but does not when routing is handled by $location.path(url).
Socket.io code(view controller):
.controller('ViewCtrl', function ($scope, $routeParams, $http, $location, socket) {
socket.connect('', { query: 'id=' + $routeParams.id });
socket.emit('msg', { data: 'key'}); //DEBUG
socket.on('connect', function(){
console.log('Socket connected');
});
socket.on('disconnect', function(){
console.log('Socket disconnected');
});
...
Routing code(main controller, frontpage):
if (data.owner == "yes") $location.path('/view/' + $scope.id());
Routing is of course secured server-side also.
Socket.io service:
.factory('socket', function ($rootScope) {
var disconnecting = false;
var socket = {};
return {
connect: function(url, query){
disconnecting = false;
socket = io.connect(url, query);
},
on: function(eventName, callback){
socket.on(eventName, function(){
var args = arguments;
if(!disconnecting){
$rootScope.$apply(function(){
callback.apply(socket, args);
});
}
else {
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);
}
});
})
},
disconnect: function(){
disconnecting = true;
socket.disconnect();
},
socket: socket
};
});
I've also tried using socket.io directly in the controller(no service), same outcome.
The console does not give any errors either.
One solution is using socket.io for the whole app, communicating page-id, etc with emits. But this seem to be a waste when I only need socket.io at this "view-page".
EDIT: This is where it goes wrong(should not have omitted this):
$scope.$on('$destroy', function (event) {
// disconnect socket when leaving page
socket.disconnect();
});