Swapping out a setTimeout() function for an Observable in an Angular Reactive Form

I am looking to upgrade from using a setTimout() to implementing an Observable in an Angular reactive form.

Within a grandchild component of mine that handles a section of a larger reactive form, I fetch an array of data objects from an API endpoint. This data is then packed into a Form Array and submitted to the form successfully.

The issue arises due to the asynchronous nature of our API calls, causing the form data in this grandchild component to display outdated information briefly before being replaced by the updated data. To tackle this, we have resorted to using a setTimout() with a delay of 500 ms, which solves the problem on the front end.

However, relying solely on setTimeout() poses challenges for our end-to-end testing, as it often completes before the new data loads in. Moreover, using a fixed timeout is not a sustainable solution for handling async issues, especially considering that there may be scenarios where data retrieval takes longer than half a second (even if uncommon).

I aim to replace the current timeout setup with an observable, offering a more robust solution that does not hinder our testing process and can manage async operations more effectively. My struggle lies in getting the observable to function correctly, given my limited experience with RxJS.

This snippet showcases the initial function utilizing setTimeout:

setTimeout(() => {
      this.dataRow = [];
      for (let item of this.data.row) {
        this.dataRow.push(item);
      }
    }, 500);

Here is my attempt at refactoring using an Observable:

this.dataRow = [];
   this.dataEmitter = from(this.data.row).pipe(delay(1000)).subscribe(data => this.dataRow.push(data);)

While my code sets up a data stream, it seems to lack the same functionality as the timeout method. How can I achieve the desired outcome? Is my current approach appropriate for resolving this issue?

Answer №1

UPDATE:

this.dataEmitter = of(this.data.row).pipe(delay(1000)).subscribe(row => {
  for (let item of row) {
    this.dataRow.push(item);
  }
}

delay(1000) will pause emitting for 1 second. It appears that your current code is inaccurate - trying to push(row) when row is actually undefined.

If this.data.row is an Object, you'll need to transform it into an iterable format (like an array) in order to emit it in parts.

Alternatively, if you simply wish to remove the setTimeout:

this.dataEmitter = from([this.data.row]).pipe(delay(1000)).subscribe(row => {
  for (let item of row) {
    this.dataRow.push(item);
  }
}

Answer №2

Here is an example of how your code should look:

this.rowData = []

from(this.data.rows)
 .pipe(delay(500))
 .subscribe(result => {
   for(let value of result) {
     this.rowData.push(value);
   }
 }) 

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

When utilizing JSON data in node.js, the .find() method may return undefined

I am currently working on a node server and my goal is to display JSON data when a specific ID is clicked. I have configured a dynamic URL that will retrieve the data of the clicked video using parameters and then compare it with the data in the JSON file ...

Step-by-step guide on setting up multiple tabs in Ionic to work with Firebase

I've been working on developing an offline-accessible application, but I'm facing some challenges. When I test the app without an internet connection, the cached data doesn't display properly. However, if I first open the app online and then ...

Error: Attempting to access the 'style' property of a non-existent element

function showNotes() { var ThemeValues = "<%=str3%>" if (ThemeValues.value == "MyCity-Social") { document.getElementById("TextBox1").style.visibility = "visible"; document.getElementById("TextBox2").style.visibility = "v ...

Enter text into a field on a different webpage and verify if the output matches the expected result

Possible Duplicate: Exploring ways to bypass the same-origin policy I'm facing a scenario where I have a form on my website that requires validation of a number. The validation process involves checking this number against another website where e ...

Trouble with Mocha async hooks execution?

I keep encountering the issue of receiving 'undefined' for the page in this setup. It appears that none of Mocha's hooks are being executed. I've attempted adding async to the describe at the top level, used done statements, and even tr ...

I would like to showcase the quantity of students from the database on a card

Student Controller @GetMapping("/numberStudent") @ResponseBody public String getStudentNumber(){ String repot = null; repot = studentRepository.StudentsNBR(); return repot; } Student Repository @Query("select count(e) f ...

Alter the subview in real-time

When using EmberJs, I need to develop a view that can hold different types of players (such as Youtube, Photosynth, Html Content, etc.) and it should change dynamically based on a controller property that specifies the item to play. I've already crea ...

Disabling a hyperlink when a media query identifies a particular browser size

I have a grid of 20 images that open a larger version in a slideshow when clicked or touched. However, I want to disable this feature on mobile devices with screens smaller than or equal to 480 pixels. Here is an example of how it currently works: <di ...

conceal any unnecessary space occupied by setting visibility to hidden

Hey there, I'm trying to get rid of the extra space caused by using visibility:hidden. When I choose sort by date, the default content is displayed as expected. However, when I select sort by topic, it appears below the output for sort by date. I don& ...

Ways to keep the position of an expanded collapsible table from Material UI intact

I found a collapsible table code snippet on this website: https://mui.com/material-ui/react-table/#collapsible-table However, there seems to be an issue where when I expand a row, the table "grows up" as it increases in size. This behavior is not ideal. I ...

Implementing a Loop to Display Multiple Divs in Angular

<div ng-repeat="10">Text</div> I am looking for an Angular solution without using any other framework or AngularJS. It must be compatible with the latest version of Angular and should not require any additional objects. ...

utilize switchMap to terminate an HTTP request within an ngrx effect

Behold the ngrx effect in question: @Effect() throwError$: Observable<Action> = this.actions$.pipe( ofType<notificationActions.ErrorThrow>( notificationActions.ActionTypes.ThrowError ), tap(() => { this.store.dispa ...

The jQuery validation code is functioning properly, yet it is resulting in the same files being uploaded to both separate folders

Below is the query code I am using, and it seems to be working well: $("#formAbout").validate({ ignore:[], errorPlacement: function (error, element) { var lastError = $(element).data('lastError'), ...

Return a string to the client from an express post route

I'm attempting to return a dynamically generated string back to the client from an Express post route. Within the backend, I've set up a post route: router.post('/', async (req, res) => { try { // Here, I perform computations on ...

The Vue template syntax utilizes double curly braces for incrementing values within must

Embarked on learning Vue.js recently and I am intrigued by the unusual behavior in my simple code. I cannot seem to figure out what is going wrong. I am attempting to increment a counter inside mustache syntax, but something strange is happening with this ...

How can I remove the most recently added div using JavaScript?

Currently, I am expanding my knowledge in Javascript and encountered a problem. There is a function set up to add boxes every time I click "Add Data". I can continue adding multiple boxes this way, but I need assistance with implementing a button labeled " ...

What is the most effective way to compare a nested array using the map or filter function in order to return only the first match

Here is a code snippet showcasing the data object containing information for the codeworks array with code and text values. There is a key array named code = ["ABC","MDH"] and the expected output is displayed in the following code snippets. const data = ...

Error: The jQuery Django context dictionary is throwing an error due to an unexpected token "&"

I'm encountering an issue when trying to set a jQuery variable in my Django html template by assigning a context dictionary. The error message appearing in the browser's console reads: Uncaught SyntaxError: Unexpected token & This is how I& ...

Retrieving a particular object/item based on its id using Firebase

Currently in the process of developing a small web app using Firebase and React, I am encountering difficulty retrieving specific items from Firebase on the client-side of React. In traditional JavaScript, a basic fetch request might appear as follows: ...

Newer Android versions running on KitKat (4.4) and beyond may experience incomplete page loading when using Chromium web

While most website pages perform well on Android 4.4 and newer versions with Chromium-based webview, I have encountered an issue wherein a particular page behaves differently between the newer versions and the earlier Android systems. The webview function ...