ruby on rails - Messaging app using angularjs $watch and $interval -
i trying add messaging angular app has rails backend. make messaging feel 'real time' using $interval directive make calls server , conversation between 2 users every 5 seconds. using $watch @ messages , see if object has change , if has display new conversation.
code:
$scope.messages = messages.messages getnewmessage = -> conversation.getconverationbetweentwousers($stateparams.userid).then ((messages) -> $scope.messages = messages.messages ), (error) -> $state.reload() checkfornewmessages = -> $interval(getnewmessage, 5000) $scope.$watch('messages.messages', checkfornewmessages, true)
can please explain me why need use websocket instead of approach? also, if doing bad idea can please explain why , better approach.
please keep in mind have users conversations , solution accommodate existing conversations.
websockets allows real time. don't have fetch data client side. websockets open connection between server , client allows server push new data client has been received.
you changing way data transmitted.
with websockets, whenever new message generated client emitted server, listens new message event. relays message emitting event clients should receive message.
the event listened , can carry payload (i.e., message , user information)
example: client a: emits 'newmsg' event payload of '{user: user123, msg: message, room: 512}' server listening 'newmsg' event. on 'newmsg' event, server emits payload event, maybe like: socket.emit('512', '{user: 1234, msg: message}')
now, clients connected server , listening '512' event receive message. can add whatever sort of database transactions in when server relaying messages, in order capture conversations.
i can't speak rails specifically, sockets listeners simple set - create listener function , assign specific event it. when event triggered run whatever logic need to. no fetching data , checking changes.
something like:
socket.on('myevent', function(data) { //do cool data stuff })
Comments
Post a Comment