top of page

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
    {
        if(localStorage.getItem('your-app@userToken')===undefined)
        {
            this.eventSource.close();
        }
    }
}

You should call “close()” method if you want to end your event-stream connection. You may have created a Subscription and have “unsubscribed” it in your ngOnDestroy method but this will not close the connection. In your case, “if” condition in “closeEventSource” method may differ but do not forget to call “close()” when you no longer need data from SSE (you can maybe check error reason to close or try to reconnect).



Source: Medium - Señorita Developer


The Tech Platform

0 comments
bottom of page