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

  • 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(‘’)(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 ‘’; 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) => {; }); 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:, selector: ‘chat’, template: `

  • 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. with RxJs in Angular

Comments are closed, but trackbacks and pingbacks are open.