Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with:

objs = []

getObjs() {
    let counter = 0
    this.myService.getObjs()
      .map((obj) => {
        counter = counter > 5 ? 0 : counter;
        obj.col = counter;
        counter++;
        return view
      })
      .subscribe((obj) => {
          console.log(obj);
          this.objs = obj;
          // I tried this too :
          // this.zone.run(() => {
          //   this.objs.push(obj);
          // });
    }
    , (err)=> console.warn('error in stream', err));
}

The method this.myService.getObjs listens to events from an SSE stream. Here's how it's implemented:

  getObjs(){
      var es = new EventSource(this.API + '/stream');
      return Observable.create((observer: any) => {
            es.onmessage = (event) => {
                let msg = JSON.parse(event.data)[0];
                if(msg === "complete"){
                    console.log("received 'complete' signal from server");
                    es.close();
                    observer.complete();
                }
                observer.next(msg);
            };
        });
  }

I invoke the above method in ngOnInit and expect the template to update as new events arrive. Template structure is as follows:

<div class="col-md-2">
    <thumbnail-dirictive [v]="view" *ngFor="let obj of ( objs | column: 0 )"></orbit-thumbnail>
</div>

While the stream events are logged correctly, the template does not update sequentially based on event arrival time.

I have attempted various solutions including using async pipe in the template, passing values through toArray() method, and also attempting to use reduce function with no success. Is there a working example available for handling irregular stream data updates within ngFor loop?

Edit 1: package.js file info provided below:

{
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0"
  }
}

Edit 2: Code snippet for the columns pipe registered in app module provided below :

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'column'})
export class columnPipe implements PipeTransform {
  transform(views, col: number): Array {
    return views.filter((view) => {
      return view.col === col;
    });
  }
}

Answer №1

From what I can see, your code appears to be in good shape. If this.objs = obj; is assigning the correct values, then it might be worth exploring other areas for potential issues:

  • The ngOnInit function is executed before the components template is generated. However, this shouldn't pose a problem unless you have made adjustments to the Component's ChangeDetectorRef.

  • Try outputting both objs and objs|column:0 within your code:

    <div class="col-md-2">
        {{ objs|json }}
        {{ objs|column:0|json }}
        <thumbnail-dirictive ... />
    

    This will help verify that the content is as expected and confirm that the column pipe functions correctly (it can be challenging to determine without understanding the data structure).

  • Review the section in your template that reads:

    <div class="col-md-2">
        <thumbnail-dirictive ...></orbit-thumbnail>
    

    It appears there may be an error here. Have you confirmed that this section is not causing the issue?

If none of these suggestions resolve the issue, consider creating a basic plnkr or jsfiddle to demonstrate where the problem arises.

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

The event handler cdkDropListDropped="drop($event)" is not triggering when interacting with a Material table that has a

Currently, I am working on implementing a column drag-and-drop feature using mat-table and cdkDragDrop in Angular (specifically with Angular 8). Here is the progress I have made so far: Within the component.html file: <mat-table cdkDropList cdkDrop ...

Creating a custom type for the parameter of an arrow function in Typescript

I need assistance defining the type for an object parameter in an arrow function in TypeScript. I am new to TypeScript and have not been able to find any examples illustrating this scenario. Here is my code: const audioElem = Array.from(videoElem.pare ...

The output of the incorrect .bind() example is not as

I recently came across the .bind() method while learning JavaScript. The example I found on MDN here was quite helpful, but I decided to add some console.log() statements for better understanding. this.x = 9; // Here 'this' refers to the glob ...

Creating a personalized pivot-table using the WebDataRock Javascript library with a unique configuration based on a

I'm having trouble getting this demo to work with the "hierarchy" parameter. Even when I specify the parameter value, it seems to apply the condition to the entire hierarchy chain. "conditions": [{ "formula": "#val ...

Unable to alter fxFlex property within Component using "setAttribute('fxFlex', '25%')" does not function properly in Angular 6

Currently, I am utilizing the flexLayout module to create responsive divs in my Angular application. You can find more information about flexLayout at https://github.com/angular/flex-layout and also at https://alligator.io/angular/flex-layout/. const nav ...

Is it acceptable for Single Page Web Apps to have multiple requests at startup?

I've been dedicated to developing a Single Page Web App (SPA) recently. The frontend is built with BackboneJS/Marionette, while the backend is powered by Java Spring :(. However, I've noticed that the application's start time could be sluggi ...

Switch up the position of an element every time the page is refreshed

I have a webpage containing 5 images, each measuring 48px by 48px. I would like these images to be displayed in random positions on the page every time it is loaded. While I am aware that I will need to use CSS and JavaScript for this task (specifically f ...

Utilize recursive and for loop methods for parsing JSON efficiently

I have a JSON file that requires parsing. I'm attempting to implement a recursive method for this task. The current JSON data is structured as shown below: Item 01 SubItem 01 InnerSubItem 01 Item 02 SubItem 01 InnerSubItem 01 Unfortunately, t ...

Issue with Submit Button Functionality following an Ajax Request

I am facing an issue where the submit button does not work after an ajax call, but works fine if I reload the page. The problem arises when a modal is displayed for email change confirmation. If the user confirms the change, the form submits successfully. ...

Text input fields within a grid do not adjust to different screen sizes when placed within a tab

I noticed that my component under a tab is causing the Textfield to become unresponsive on small screens. To demonstrate this, I checked how the Textfield appears on an iPhone 5/SE screen size. https://i.stack.imgur.com/d8Bql.png Is there a way to make t ...

Enhance your AJAX calls with jQuery by confidently specifying the data type of successful responses using TypeScript

In our development process, we implement TypeScript for type hinting in our JavaScript code. Type hinting is utilized for Ajax calls as well to define the response data format within the success callback. This exemplifies how it could be structured: inter ...

Steps for integrating an Angular 2 App into Express.js as a view

I am currently working on developing an Angular 2 app that requires data from a script running on the server. To achieve this, I am attempting to integrate my existing Angular app as a view within an express application, similar to the process demonstrated ...

Tips on implementing pdf-lib in Angular?

I came across the pdf-lib library and am interested in incorporating it into my Angular project. However, I couldn't find any documentation on how to import it specifically for Angular. Can anyone assist me with the process of importing this library ( ...

Reduce the amount of time it takes for a Google AdWords Script to generate a

According to Google Script best practices, it is recommended to store operations in an array and then call the methods once all the operations have been constructed. This helps minimize response time each time a service is called. For example, let's ...

Injecting arbitrary text following ?= in a web URL

Consider the following code snippet for a page named MyWebsite.com/page.php <?php $username = "SuperUsername"; $password = "SuperPassword"; if (isset($_GET['p']) && $_GET['p'] == "login") { if ($_POST['user&ap ...

Array updating using the foreach method in Angular

Hey everyone, I've encountered an error that seems to be related to scope and I could use some advice. I'm currently looping through an array and trying to push the results to another array. However, when I attempt to push the results to public m ...

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

The server nodejs is unable to recognize the dotenv file

This is my very first project with the MERN stack and I'm currently working on pushing it to GitHub. Since I am using Mongoose, I needed to protect the login credentials for my account. After some research, I discovered the solution of using a .env fi ...

What is the best way to convert this into a distinct function using typescript?

Is there a way to create a single method in Protractor or Webdriver API that can get the browser width and height? const getWindowWidth = async () => { const size = await browser.manage().window().getSize(); return size.width; }; I need this metho ...

What sets Angular 2/4 apart is the synchronous nature of Reactive forms, contrasting with the asynchronous behavior of template-driven forms

While looking through the documentation on angular.io, specifically about reactive forms being synchronous (Reactive forms are synchronous), I found myself struggling to grasp the concept of how reactive forms differ from template-driven forms in terms of ...