Display streaming data continuously within an HTML page using Angular 16

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:

  1. 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.

Answer №1

Consider utilizing an accumulator operator such as scan (refer to the documentation here)

Here is an example from the documentation:

// RxJS v6+
import { of } from 'rxjs';
import { scan } from 'rxjs/operators';

const source = of(1, 2, 3);
// basic scan example, sum over time starting with zero
const example = source.pipe(scan((acc, curr) => acc + curr, 0));
// log accumulated values
// output: 1,3,6
const subscribe = example.subscribe(val => console.log(val));

You can add this code in your xxx function:

connectToSse(): Observable<any> {
    return new Observable((observer) => {
      this.eventSource = new EventSource(`${this.url}/getStreamingData`);
      this.eventSource.onmessage = (event) => {
        // code to manipulate string data to convert it into [object, object] so that once HTML component receives, it can be shown in browser immediately

          observer.next(ArrayObj)
      };

      this.eventSource.onerror = (error) => {
        observer.error(error);
        this.closeConnection();
      };
    })
    .pipe(
        scan((acc, curr) => { your implementation })
    );
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2 has upgraded its Controller functionality by replacing it with Component

I find it a bit challenging to distinguish between Component and Controller. How was the Controller replaced by component in Angular 2? I came across this description of a component: In Angular, a Component is a distinct type of directive that utilizes a s ...

Tips for specifying the type when utilizing the spread operator to pass props

type TypeData = { data: { id: string; class: string; name: string; country: string; ew_get_url: string; ew_post_url: string; rocket_id: string; pages: { landing: { h1: string; h2: string; } ...

How to Send Data to ASP.NET MVC Controller Using AJAX Request with jQuery

I am trying to send parameters to a controller from jQuery, but I am struggling with it. The call works fine without parameters when the URL is just /SurveySection/EditLocalization. Shouldn't it be something like this: /SurveySection/EditLocalization? ...

Issue encountered while connecting ipcRenderer with ipcMain in an electron application

I recently set up Angular CLI in Electron, and I have a link that triggers a function which communicates between ipcRenderer and ipcMain: Here is the HTML code: <a (click)="check()"> click </a> This is the component code: constructor(privat ...

Developing distinct state values for assigned objects

I developed a star rating component using Material UI components that is based on a mapped object. However, I am facing an issue where all the star ratings show the same value when clicked. How can I ensure that each star section displays its own value bas ...

Control the switch for CSS selectors

Consider the following scenario where CSS rules are defined: <style> table {background:red;} div {background:green;} </style> In addition, there is HTML code that calls a JavaScript function: <table onclick="tu ...

Currently, I am in the process of creating a game, but I am having trouble with my click event not functioning as expected on a dynamically

I'm currently working on a platform game and I've implemented a window.onload event that is supposed to trigger. Within this event, I am creating a div element, assigning it an ID, and then setting its onclick property. Despite being confident i ...

Send data to assembled Angular directives

Using a third-party directive "A" with inputs a1 and a2, I am looking to create a new directive "B" that acts as a facade for "A". The goal is to set specific values for "A" within "B" so that configuring the inputs each time "A" is used is not necessary. ...

Converting API response into a class instance using `class-transformer` in TypeScript: A step-by-step guide

When working with TypeScript, I have a regular method called Request(method: HttpMethod, url: string, ...) that is used for calling APIs. Now, my goal is to convert the response from this API request into an instance of a class using class-transformer (or ...

Is JavaScript Gallery Acting Up? Possible Layer Glitch!

Seeking assistance with a website issue. I have an index.php file set up with a sideshow script in the head that appears on all pages. Additionally, within the index.php file, there is a portfolio.html page that displays a gallery script when loaded. The p ...

Updating the div#content dynamically with Jquery without the need to refresh the page

After spending countless hours on this forum, I have yet to find a solution that perfectly fits my needs, so I will pose my question. Here is the gist of what I am attempting to accomplish: When the page loads, the default page fades in and displays. Wh ...

Transferring the state from a parent component to a child function

I'm having trouble passing a state from a component to a function. I was able to pass the state from Home to ListHome, but I'm struggling to continue passing it to a function within ListHome (Slider) because it's a function. Even after revi ...

Tips for circumventing if statements in TypeScript-ReactJS?

I currently have various action checks in place to perform different functions. Essentially, I am using if and else conditions to determine the action type and execute the corresponding functionality as shown below: public onMessage = (messageEvent) => ...

Tips on creating an object within a TypeScript interface

As a newcomer to Type Script, I am curious if there is a way to specify in the interface "IIndex" that SystemStatus is an object with properties Data and DataUrl. Currently, it appears that SystemStatus is undefined. interface IIndex extends ng.IScope { ...

Assign false to all properties in the nested object with the exception of one

In order to manage the open/close state of my panel, I am using setState similar to the method described in this post. My goal is to only allow one panel to be open at a time, meaning there will be only one true value in the state. Here is the snippet of ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

Webpack and React.js: Additional loaders might be required to manage the output generated by these loaders

An error occurred while parsing the module in ./productFlow/index.tsx at line 3, column 12. The file was processed with the following loaders: * ./node_modules/awesome-typescript-loader/dist/entry.js. It seems like an additional loader may be needed to h ...

Do arrays permanently retain the strings stored within them?

As an 11-year-old who has been learning Javascript for the past month and a half, I am currently working on creating a login/register system. Right now, my focus is on the register part. I have a question: when adding a string/number/boolean to an array, d ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

Discovering the intricacies of using *ngFor on an object in Angular with Firebase

Tools I'm Utilizing Angular Firebase My Current Setup A component that showcases information about an 'Issue' Within the issue, there is another section called 'images' Under the image node, there are additional properti ...