Reputation: 20634
I'm opening up my page in two tabs. For some reason, the client 'on' only fires once both tabs have submitted a post.
// server
io.on('connection', function (socket) {
socket.on('newPost', function (post) {
io.emit('newPostReturn', post)
console.log(post)
})
})
// client (angular)
$rootScope.socket = io('http://172.28.28.201:3000');
$rootScope.socket.emit('newPost', post);
$rootScope.socket.on('newPost', function (post) {
$scope.$apply(function () {
$scope.posts.push(post);
});
});
UPDATE:
Changed to using https://github.com/btford/angular-socket-io. Same problem. Also I notice that bizarrely after the 3rd emit each client re-runs 'on' another time. It's like the first time it triggers 'on' zero times, then every subsequent call it triggers it an additional time.
.factory('socket', function (socketFactory) {
var ioSocket = io.connect('http://172.28.28.201:3000');
socket = socketFactory({
ioSocket: ioSocket
});
return socket;
});
UPDATE 2: I'm dumb!!
I had my 'on' handler INSIDE the submit post event. Moved it outside and, of course, everything works as expected. Everything makes perfect sense now. Thanks
Upvotes: 0
Views: 200
Reputation: 16066
I'd suggest you to create a service to create a service for handling the socket.io connection; look for angular socket io which is practically a service wrapper.
you'll have a less coupled implementation and it would be easier to handle the instance and the connections.
Upvotes: 1