且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 angular.js 推送通知?

更新时间:2023-02-16 22:20:02

由于您使用的是 MEAN 堆栈,因此 Node 中的标准建议是使用 Socket.IO API.

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):

客户

<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>

服务器

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);
  });
});

它会在可能的情况下使用 websocket,并在不支持 websocket 的浏览器中回退到 AJAX 长轮询或 Flash 轮询.

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

至于与 Angular 的集成,这里有一篇关于 Socket.IO 和 Angular的好博文>:

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

我将写关于如何集成 Socket.IO 以添加实时AngularJS 应用程序的功能.在本教程中,我将演练编写即时消息应用程序.

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.