JavaScript Edu Resources. Angular Courses. React Tutorials. Join us!

Socket.io with Observables

  • Socket.io will take care of setting up the socket, but we will be using observables to receive and distribute chat messages from the server.
  • Server(app); let io = require(‘socket.io’)(http); io.on(‘connection’, (socket) => { console.log(‘user connected’); socket.on(‘disconnect’, function(){ console.log(‘user disconnected’); }); socket.on(‘add-message’, (message) => { io.emit(‘message’, {type:’new-message’, text: message}); }); }); http.listen(5000, () => { console.log(‘started on port 5000’); });

    The server is responsible for managing connections and notifying connected clients of new chat messages.

  • import { Subject } from ‘rxjs/Subject’; import { Observable } from ‘rxjs/Observable’; import * as io from ‘socket.io-client’; export class ChatService { private url = ‘http://localhost:5000’; private socket; sendMessage(message){ message); } getMessages() { let observable = new Observable(observer => { this.socket = io(this.url); this.socket.on(‘message’, (data) => { observer.next(data); }); return () => { this.socket.disconnect(); }; }) return observable; } }

    The observable is configured to emit a value every time we receive a new chat message from the server.

  • /chat.service’; @Component({ moduleId: module.id, selector: ‘chat’, template: `
    {{message.text}}

  • However, the important part to pay attention to is the subscription to the observable returned from observable will emit a new value for every new chat message and update our list of displayed messages.



Socket.io with RxJs in Angular


https://twitter.com/intent/tweet

Comments are closed, but trackbacks and pingbacks are open.