Search code examples
angularjschatmeanjs

meanjs chat implementation: not losing messages even if leaving chat module


This is a question about the best practice of implementing Socket.io in AngularJS.

In the dedicated book on the subject I found a simple chat implementation. It is realized this way:

  1. Socket.io is wrapped in a service
  2. Chat controller consumes this service to update scope variables
  3. View is updated with regarding to scope variables to show messages

I implemented it and found a problem with it but I don't know the efficient solution.

The scenario:

  1. User A is in chat with B
  2. B leaves the chat module to another module of the app
  3. A sends a message to B in this time
  4. B loses the message and will not receive it when back to chat module: only chat module implemented Socket.on!

The inefficient solution: - implement Socket.on listenner in every controller of all modules and break DRY principle! :-)

I know a little about rootScope in Angular, but is that the best way to go or where / how best to provide a solution in Angular...

So how to have it:

  1. B visiting any module of the app and Angular receives and keeps all messages sent to B
  2. Back to the chat module, B has all messages available

is the rootScope what to consider, or there are other features of AngularJS to be used?


Solution

  • I think the best way will be to store chat messages in the database. This is because in the chats.client.controller file, the $scope.message variable is initialized to null. Therefore by storing all messages in the database, we can create a service factory for querying all the messages as well as the latest message once the user is back on the chats page. This first step is help store the messages.

    For the second step, we can create a socket in the core client controller that listens for the chatMessage event. Since the core is linked to all modules, we will be able to get notified when a new message has been posted.