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

In TypeScript, the type of the second function parameter depends on the type of the first

I'm new to typescript programming. Overview In my typescript react application, I encountered an issue where I needed to dynamically watch the values returned from the watch() method in react-hook-form, based on different parameters passed into a cus ...

Attempting to monitor the frequency of calls to a JavaScript function

let totalEnteredCount = 0; function totalEntered(field){ if(field.value != '') { totalEnteredCount++; } alert(Counter); if(totalEnteredCount == 3) { var InitialVelocity = document.getElementById("IVUnit").value; var FinalVelocity = do ...

FFmpeg: audio synchronization issue observed with simultaneous usage of xfade and acrossfade techniques

Experiencing an issue when attempting to concatenate 12 videos together and maintain the audio using xfade and acrossfade filters. Without the audio stream, the video encodes correctly, but when combining with audio, transitions hang and audio sync is off. ...

Tips for conducting key down event testing on a material ui MenuList element utilizing react-testing-library

Looking to test the key down event on my MenuList component. Component: import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import * as React from 'react'; export default fu ...

What causes the input field to lose focus in React after typing a character?

Currently utilizing React Mui for components and encountering no errors in either the Chrome inspector or terminal. How can this be resolved? No error notifications are being displayed by eslint or Chrome Inspector. The form submission functions correctl ...

Changing the CSS property of a single table cell's innerHTML

I have a question that may seem silly, but I'm going to ask it anyway. Currently, I am iterating through a list of strings that follow the format "1H 20MIN" and adding them to table cells using the innerHTML property like so: for (i = 0; i < list ...

Encountered an error while attempting to complete the 'send' action with 'XMLHttpRequest'

I am currently developing a Cordova application that makes use of ajax. Everything works perfectly during debugging, but once I build the release version, I encounter this error: {"readyState":0,"status":0,"statusText":"NetworkError: Failed to execute &ap ...

Utilizing deployJava.runApplet for precise element targeting

After years of successfully maintaining an applet that utilizes the traditional: <script src="foo.js"></script> method for embedding a Java applet, we can no longer ignore the need for change. It's time to switch to: deployJava.runAppl ...

Output a variable that is generated from invoking an asynchronous function

I'm currently in the process of developing an application that is going to leverage the capabilities of a SOAP server through the use of the https://github.com/vpulim/node-soap module. One of the main challenges I am facing is how to efficiently crea ...

Showing or hiding components within ReactJS based on conditions from other components

A custom hook has been created to toggle the visibility of a list when a button is clicked. Below is the snippet of the custom hook: import { useEffect } from "react"; import { useState } from "react"; function useVisibilityStatus() { ...

Step-by-step guide on making a duplicate of a Search bar

I have a search field in my application that I want to duplicate. The goal is to create two identical search fields, one on the left side of the page and another on the right side. How can I achieve this using JavaScript? Here is my JavaScript code: doc ...

How can I effectively organize an Angular2 component library for optimal efficiency?

Looking to develop an Angular2 datepicker component with the intention of releasing it and using it in multiple projects. Wondering about the best way to structure the project for this specific purpose compared to a typical Angular2 project created with an ...

Node.js and the Eternal Duo: Forever and Forever-Montior

Currently, I am utilizing forever-monitor to launch a basic HTTP Node Server. However, upon executing the JavaScript code that triggers the forever-monitor scripts, they do not run in the background. As a result, when I end the TTY session, the HTTP server ...

Troubleshooting problem with iPhone X responsiveness

Struggling with responsive issues on iPhone X. Issue is only appearing on actual device. Any tips for fixing this? I'm facing an issue where the website looks good and responsive on all devices in Chrome's responsive view. But when I access it th ...

Issue with reactivity not functioning as expected within VueJS loop without clear explanation

Struggling with implementing reactivity in vue.js within a loop? The loop renders fine, but firing an event updates the content without visibly rendering the data on the page. The latest version of vue.js is being used with bootstrap and jquery. Despite a ...

Locate and refine the pipeline for converting all elements of an array into JSON format using Angular 2

I am currently working on implementing a search functionality using a custom pipe in Angular. The goal is to be able to search through all strings or columns in a received JSON or array of objects and update the table accordingly. Here is the code snippet ...

Ensure that the HTML input element only accepts positive values, including decimal numbers

I need to build an input field that only accepts positive numbers, including decimal values. Leading zeros are not allowed, and users should not be able to paste invalid values like -14.5 into the field. Here is my current implementation: <input type= ...

Refreshing the webpage section without requiring a full page reload

I am currently working on a Django website and I have been trying to update a specific section of the webpage without refreshing the entire page. However, most solutions I found online didn't work for me because the part I want to update is actually i ...

Identify the failing test cases externally using JavaScript

I am currently tackling an issue where I am seeking to identify the specific test cases that fail when running a test suite for any javascript/node.js application. Finding a programmatic solution is crucial for this task. Mocha testsuite output result Fo ...

Implementing a 'Load More' button for a list in Vue.js

I am currently working on adding a load more button to my code. While I could achieve this using JavaScript, I am facing difficulties implementing it in Vue.js. Here is the Vue code I have been working with. I attempted to target the element with the compa ...