简体   繁体   中英

How best to integrate socket.io with rest in Angular2

I want realtime updates in my Angular (6) app when users interact with the database so i'm using socket.io to do this.

For example I have a job component/form/service and my current approach is to:

  • submit the job from job-form to job.service :
  • this calls an http post to express (and returns an observable):

     return this.http.post(api_url + '/jobs/', job); 
  • insert the job into mongoDB and return success

  • when observable receives success call a function on my socket.service which emits a socket message to the server
  • the server hears this and emits a 'refreshJobs' message to all clients
  • socket.service hears this and updates the jobs from job.service

This works fine but seems very long-winded... is there a better way to do this? I could just use socket and bypass the Express REST api?

Basically, you are posting job to server, after that you get success on client and then again pushing success trough socket and then stream via socket.io to others in frontend. Better way is to emit new job via socket, in socket you can save new job and after success you can emit to everyone. Another approach is to listen for changes in mongoDB ( https://www.mongodb.com/blog/post/an-introduction-to-change-streams ) and emit to others.

And maybe best approach is this:

const app = express();
const server = require('http').Server(app);
const io = require('socket.io').listen(server);
app.set('socketio', io);

And in your routes for example you can do this:

var io = req.app.get('socketio');
io.emit('room', 'hi'); // this will emit 'hi' in room 'room'

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