Event Source with Angular

Gul Ershad
ITNEXT
Published in
3 min readJun 11, 2018

--

Introduction

Event Source is a part of SSE (Server-Sent Events). It pushes data to the browser by providing one-way communication between the server to the browser. Here, communication is carried out from server to browser only and browser doesn’t send any data to the server.

Example of Event Source

  1. Auto-update of Cricket scores on the website.
  2. Auto-update of Online stock price update.
  3. Auto-update of Weather information like temperature, humidity, rain forecast, etc.
  4. Twitter updating timeline.
Event Source between Angular and Java (spring boot)

Event Source or SSE Vs Web-socket

Event Source

  1. It is a server sent a communication that is carried out from server to web browser client only. It supports one-way communication.
  2. It doesn’t support binary. Its uses only UTF-8.
  3. It has a maximum open connection limit.
  4. It has built-in support for re-connect and event Id.

Web-socket

  1. It provides two-way, a full-duplex communication over a single TCP connection.
  2. Data can be communicated from server to browser, vice versa. Online chat is the best example.
  3. It supports arbitrary binary data.

Code Discussion

Service Class (spring boot)

Here, the Service class receives data from some data source and gives it to the controller class like below:

package com.myservice;import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.philips.models.WorkflowDataModel;
@Service
public class StatusInProgress {
private static Map<String, String> storeData = new HashMap<String, String>();@Override
public void triggerEvent(MyDataModel eventData) {
System.out.println("Display To Angular App");
try {
System.out.println(eventData.getPatientId());
ObjectMapper mapper = new ObjectMapper();
String jsonText = mapper.writeValueAsString(eventData);
putPatient(jsonText);
} catch (IOException e1) {
e1.printStackTrace();
}
}
@CachePut(value = "myData")
public void putMyData(String myData) {
if (storeData.containsKey("mydata")) {
storeData.remove("mydata");
}
storeData.put("mydata", patientData);
}
@Cacheable(value = "myData")
public String getMyData() {
String myitem= "";
try {
myitem = storeData.get("mydata");
} catch (Exception e) {
}
return myitem;
}
}

Controller Class (spring boot)

The controller class receives data from the service class and emits the data by REST API. It uses SseEmitter.

package com.controller;import java.io.IOException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;import com.myservice;@Controllerpublic class MyDataController {@Autowiredprivate StatusInProgress statusInProgress;@CrossOrigin(exposedHeaders = "Access-Control-Allow-Origin")@RequestMapping(value = "/get_mydata")public SseEmitter getMyData() throws InterruptedException {SseEmitter notifier = new SseEmitter(600L);try {String myData = statusInProgress.getMyData();if (myData!= null && myData!= "") {notifier.send(SseEmitter.event().reconnectTime(500).data(myData));}} catch (IOException e) {e.printStackTrace();}return notifier;}}

Component (Angular 4)

This component TypeScript class subscribes the API from Server like below:

import { Component, OnInit } from '@angular/core';
import {Observable} from "rxjs";
@Component({
templateUrl: './app/home/home.html'
})
export class HomeListComponent{
myData: any;

constructor(private airService: AIRadiologyService) {
this.connect();
}
connect(): void {
let source = new EventSource('http://serverip:port/get_mydata');
source.addEventListener('message', message => {
this.myData = JSON.parse(message.data);
});
}
}

Conclusion

The event source is very good to update or refresh browser data with real-time data. This protocol is very less complicated because it gives flexibility by not adding any external JavaScript library. JavaScript itself provides the EventSource interface to receive the real-time data or message sent by the server.

--

--

A technology explorer with the drive to learn, apply and expand his mind.