简体   繁体   中英

loopback access model data and emit using socketio

I'm using Loopback as my backend and Angularjs in frontend. The requirement is to emit data based on some interval to all the connected clients.

This is my server.js file:

var loopback = require('loopback');
var boot = require('loopback-boot');   
var app = module.exports = loopback();

app.start = function() {
  return app.listen(function() {
    app.emit('started');
    var baseUrl = app.get('url').replace(/\/$/, '');
    console.log('Web server listening at: %s', baseUrl);
    if (app.get('loopback-component-explorer')) {
      var explorerPath = app.get('loopback-component-explorer').mountPath;
      console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
    }
  });
};

boot(app, __dirname, function(err) {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module) {
    //app.start();
    app.io = require('socket.io')(app.start());
    app.io.on('connection', function(socket){
      console.log('a user connected');
       var runs = app.models.runs;
       setInterval(function(){
          //  socket.emit('model', Model.find({limit : 500})); 
        }, 2000);

      socket.on('disconnect', function(){
        console.log('user disconnected');
      });
    });
  }

});

Here I'm trying to access my model and emit it, but I'm not able to figure out how to access the model data.

Well it, seems like you already got what you want from your code, not sure what's the problem. Based on the requirement you can change your code to this and it should work:

var runs = app.models.runs;
setInterval(function(){
  runs.find({limit : 500})).then(function(results){
    socket.emit('model', results);
  }).catch(console.error);
}, 2000);

Couple of things to note here.

  • Don't forget proper error handling.
  • The results variable will be an array with 500 documents inside it. Looks huge to me and it might have bad performance. Careful about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM