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?