How to push notifications with angular.js?

Francesco Gallarotti picture Francesco Gallarotti · Dec 1, 2013 · Viewed 37k times · Source

I have been building a simple application to learn angular.js. So far I hooked up all the pieces in the MEAN stack and I am able to save and retrieve data from Mongo.

The app is essentially a todo list. The user can create a project and inside the project create "cards" with "todos" which can then be moved from state to state ("backlog", "in progress", "complete", etc.)

I would like to be able to push the notifications to all the people who are connected to tell their apps that a refresh is needed to get the latest todos. In other words, let's say that user A adds a new card to project A, I would like to send a message out to all users who are currently watching project A so that their application issues a project refresh to get the latest and greatest.

Any suggestions on how to proceed? Which technology, if any, I need to add to the MEAN stack to be able to do something like this?

Thanks in advance

Answer

Ryan Weir picture Ryan Weir · Dec 2, 2013

Since you're on the MEAN stack, the standard recommendation in Node would be to use the Socket.IO API.

They provide the following example of two way messaging (which would facilitate your push messages very easily):

Client

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Server

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

It will use websockets where possible, and fallback to AJAX long polling or Flash polling in browsers where there is no websocket support.

As for integrating with Angular, here's a good blog post on Socket.IO and Angular:

I'll be writing about how to integrate Socket.IO to add real-time features to an AngularJS application. In this tutorial, I'm going to walk through writing a instant messaging app.