Currently, I am actively developing a stream API that receives data with a 'Content-Type' of 'text/event-stream'.
Below is a snippet from my stream.service.ts:
connectToSse(): Observable<any> {
return new Observable((observer) => {
this.eventSource = new EventSource(`${this.url}/getStreamingData`);
this.eventSource.onmessage = (event) => {
// Implement code here to transform string data into [object, object] format for immediate display in the browser
observer.next(ArrayObj)
};
this.eventSource.onerror = (error) => {
observer.error(error);
this.closeConnection();
};
});
}
Now, moving on to html.component.ts:
getStreamData() {
this.sseSubscription = this._stream.connectToSse().subscribe(
(event: any) => {
// Here, one-by-one or sometimes in pairs or groups of 2/3, I receive the newly parsed array object
this.accumulatedData$ = of(event);
},
(error: any) => {
console.error('SSE error:', error);
}
);
}
The HTML TEMPLATE section shows how the data is displayed in the HTML:
<div class="json-container">
<div *ngFor="let row of accumulatedData$ | async;">
<ng-container *ngFor="let item of row | keyvalue">
<div class="">
{{item.key}} || {{item.value}}
</div>
</ng-container>
<hr />
</div>
</div>
While I can successfully display the data in the HTML once all the array objects are received, I am encountering a specific issue.
Current challenge:
- With the current code, only the last received array objects are displayed after all the data is received. Attempting to push the objects one by one with an additional variable also results in displaying all the objects once the data/stream is completely loaded.
Issue: I am striving to display the data in the browser as soon as it is received within the component.ts file. Despite utilizing ngZone, detection strategies, and other observables methods, the current code scenario remains unaffected.