samedi 18 avril 2015

Update data sent via sockets using angular with Sails Js

So im building a simple real time chat app in which i can have multiple rooms, each room with multiple users and multiple messages also. Im wondering if this is a common problem with sockets or maybe im doing something wrong, but whenever a user access a room, for instance its being pushed correctly and for instance it is not. For example it happens that i have 2 browsers opened with 2 different users logged in the same room and when i log some of the users to another room then its again being pushed to the room it was before, unless you refresh both browsers. Also.. how can i avoid each user being pushed multiple times in the same room if it logs out and log in back again? Any help would be appreciated.



angular.module('app')
.controller('RoomController', function($scope, $stateParams, Room, User, Message, CurrentUser) {

var currentUser = CurrentUser.user;
$scope.users = [];
$scope.access = accessRoom;
$scope.leave = leaveRoom;

listenRoomActions();

function listenRoomActions() {
io.socket.on('room', function(data) {
if (data.verb === 'addedTo' && data.attribute === 'users') {
var userId = data.addedId;
User.get(userId).then(function(user) {
angular.forEach($scope.users, function(item, index) {
if (userId !== item.id) {
$scope.users.push(user.data);
}
});
});
} else {
if (data.verb === 'removedFrom' && data.attribute === 'users') {
var userId = data.removedId;
var whatIndex = null;
angular.forEach($scope.users, function(item, index) {
if (item.id === userId) {
whatIndex = index;
}
});
$scope.users.splice(whatIndex, 1);
$scope.$apply();
}
}
});
};

function accessRoom(id) {
io.socket.post('/room/' + id + '/users/' + currentUser().id, function(data) {
console.log(data);
});
};

function leaveRoom() {
var id = $stateParams.id;

io.socket.delete('/room/' + id + '/users/' + currentUser().id, function(data) {
console.log(data);
});
};
});

Aucun commentaire:

Enregistrer un commentaire