How to Call Event-Stream APIs in Angular

In this post, we will tell you how this API was called in Angular (to refresh inbox when a new mail arrives or a mail is sent to trash in another device, etc.)


Firstly, install event-source-polyfill from npm:

npm i event-source-polyfill

EventSourcePolyfill enables you to send header parameters. Below is the service implementation:

import{Injectable} from'@angular/core';
import{Observable} from'rxjs/Observable';
import{EventSourcePolyfill} from'event-source-polyfill';
import{environment} from'@environments/environment';
import{DeviceDetectorService} from'ngx-device-detector';

@Injectable()
export class EventStreamService{
    eventSource: EventSourcePolyfill;
    
    constructor(private deviceDetectorService: DeviceDetectorService){}
    
    getSocketEvents(): Observable<any>
    {
        return new Observable((observer)=>
        {
            this.eventSource = new EventSourcePolyfill
                                                    (environment.sse_url,
            {
                headers: 
                {
                    'Authorization': 'Bearer '+localStorage.getItem('your-
                                                        app@userToken'),
                    'Device-Language': navigator.language,
                    'Device-Name': this.deviceDetectorService.os+' - 
                            '+this.deviceDetectorService.browser+' 
                            '+this.deviceDetectorService.browser_version,
                    'Device-OS': 'WEB'
                }
            });
            
            this.eventSource.onmessage=(event)=>
            {
                observer.next(event.data);
            };
            
            this.eventSource.onerror=(error)=>
            {
                this.closeEventSource();
            };
        });
    }
    
    closeEventSource(): void
    {