如何设置socket.io以获取实时数据

时间:2019-01-26 04:01:43

标签: node.js angularjs express socket.io mean-stack

我是平均值堆栈的新手,我遵循了一些有关如何获取实时数据的说明。我尝试了每个步骤,但都无法正常工作,如何正确使用socket.io?我在此处提供了用于从mongodb吸引用户的代码,请更正我的代码

server.js

var express     = require ('express');
var app         = express();
var server      = require('http').Server(app);
var http        = require('http').Server(app);
var io          = require('socket.io')(http);
var morgan      = require ('morgan');
var mongoose    = require('mongoose');
var appRoutes   = require('./app/routes/api');

app.use(morgan('dev'));
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(express.static(__dirname + '/public'));
app.use('/api',appRoutes);

mongoose.connect('mongodb://localhost:27017/testing', function(err){
    if(err){
        console.log('Not connected' + err);
    } else
    {
        console.log('Connected');
    }
});

然后这是我从表中获取用户的部分,我不知道如何实时获取数据:

api.js

var User = require('../models/user');
const router = express.Router();
router.get('/management', function(req, res) {
        User.find({}, function(err, users) {
                if (!users) {
                    res.json({ success: false, message: 'Users not found' }); 
                } else {
                    res.json({ success: true, users: users,});
                }
        });
    });

userCtrl.js

.controller('managementCtrl', function(User, $scope) {
 function getUsers() { 
        User.getUsers().then(function(data) {
            if (data.data.success) {
                app.users = data.data.users;    
            } else {
                app.errorMsg = data.data.message; 
            }
        });
    }
});

userServices.js

angular.module('userServices', [])

.factory('User', function($http) {
 var userFactory = {}; 
 userFactory.getUsers = function() {
        return $http.get('/api/management/');
    };

 return userFactory;
    });

};

users.html

<tbody>
    <tr ng-repeat="person in management.users">
        <td align="center">{{ person.name }}</td>
        <td align="center">{{ person.email }}</td>
    </tr>
</tbody>

1 个答案:

答案 0 :(得分:0)

您必须与frontEnd建立持久的套接字连接。建立持久连接后,您必须侦听特定事件,然后发送实时用户数据。
您可以通过以下方式实现:

server.js

 var express     = require ('express');
var app         = express();
var server      = require('http').Server(app);
var http        = require('http').Server(app);
var io          = require('socket.io')(http);
var morgan      = require ('morgan');
var mongoose    = require('mongoose');
var appRoutes   = require('./app/routes/api');
var User = require('../models/user');

app.use(morgan('dev'));
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(express.static(__dirname + '/public'));
app.use('/api',appRoutes);

mongoose.connect('mongodb://localhost:27017/testing', function(err){
    if(err){
        console.log('Not connected' + err);
    } else
    {
        console.log('Connected');
    }
});

io.on('connection', function(socket) {
  console.log('New Socket has been connected');
  socket.on('getUserDetails', function() {
    User.find({}).then(function(data){
      socket.emit('userDetails', data)
   })
  })
})

在fronEnd中,您可以发出事件 getUserDetails 以从服务器获取数据,并监听 userDetails 以从服务器获取响应。

类似的事情可以在前端实现 angular