After filling a Set with asynchronous callbacks, attempting to iterate over it with a for-of loop does not accept using .entries() as an Array

Encountering issues with utilizing a Set populated asynchronously:

    const MaterialType_Requests_FromESI$ = SDE_REACTIONDATA.map(data => this.ESI.ReturnsType_AtId(data.materialTypeID));

    let MaterialCollectionSet: Set<string> = new Set<string>();

    let MergedMaterialTypes$ = merge(MaterialType_Requests_FromESI$);

    MergedMaterialTypes$.subscribe(
      MaterialType$ => MaterialType$.subscribe(MaterialType => MaterialCollectionSet.add(MaterialType.name)),      
      null,
      () => {
        console.log(MaterialCollectionSet);      // Shows Set object with 'size' of 98
        console.log(MaterialCollectionSet.size); // Displays 'size' as 0        
      }
    );

Upon logging the Set, an Object is returned with size property 98 and an 'Entities' Array containing values...

However, directly accessing the size property yields a value of 0...

Furthermore, Set.entries() can't be used in a for-of loop as an Array, even when converting using Array.from()...

    const MaterialType_Requests_FromESI$ = SDE_REACTIONDATA.map(data => this.ESI.ReturnsType_AtId(data.materialTypeID));

    let MaterialCollectionSet: Set<string> = new Set<string>();

    let MergedMaterialTypes$ = merge(MaterialType_Requests_FromESI$);

    MergedMaterialTypes$.subscribe(
      MaterialType$ => MaterialType$.subscribe(MaterialType => MaterialCollectionSet.add(MaterialType.name)),      
      null,
      () => {

        // Loop doesn't execute despite having 98 Entries
        for(let entry of Array.from(MaterialCollectionSet.entries())) {
          console.log(entry)
        }

        // console.log(MaterialCollectionSet);      // Shows Set object with 'size' of 98
        // console.log(MaterialCollectionSet.size); // Displays 'size' as 0        
      }
    );

Referenced sources suggesting for-of loops should work, but they are not.

Where and how am I incorrectly accessing this Sets properties???

Answer №1

After making the switch from using 'merge' to 'forkJoin', I was able to successfully resolve the issue:

    let MaterialType_Requests_FromESI$ = SDE_REACTIONDATA.map(data => this.ESI.ReturnsType_AtId(data.materialTypeID));

    let MaterialCollectionSet: Set<string> = new Set<string>();

    forkJoin(MaterialType_Requests_FromESI$).subscribe(
      MaterialTypes => MaterialTypes.forEach(Type => MaterialCollectionSet.add(Type.name)),
      null,
      () => {
        for(let entry of Array.from(MaterialCollectionSet.entries())){
          console.log(entry[0]) // [0] selects the key of the Set, which is the same as the value of the Set at [1]
        }
      }
    );

I realized that by using 'merge', I had to subscribe separately to each Observable it merged. This caused the initial subscription's completion callback to fire before the Set was fully populated.

Switching to 'forkJoin' allowed direct handling of the response data, resulting in a properly populated Set that could be easily iterated over with a 'for-of' loop.

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

Conceal dynamically generated div elements created with ngIf

I am currently working on initializing this div using ngOnInit in Angular ngOnInit(): void { let optTemp = ''; for (let data of arrOption) { optTemp = optTemp + '<option>' + data.trim() + '</option> ...

An issue arose during the installation of the package 'npm i angularfire2'

I am currently working on an Angular project and I am trying to import AngularFireStorage using the following line of code: import { AngularFireStorage } from 'angularfire2/storage'; I attempted to do this by running the command npm i angularfire ...

The observer error silently assumes an undefined type

Currently, I am attempting to implement the guidance provided in this Stack Overflow post on performing a File Upload using AngularJS 2 and ASP.net MVC Web API. The issue arises from the upload.service.ts file where an error is identified next to the prob ...

Creating a database using Angular2+ in CouchDB can be achieved by following these steps

I have been attempting to set up a database in couchdb using angular2+. My goal is to create a button that, when clicked, will initiate the creation of the database. However, I keep encountering an error message. "ERROR Error: Uncaught (in promise): H ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

Dynamically render a nested component, created within the parent component, using a directive

Can a nested component be dynamically rendered as a directive within the parent component? Instead of using the standard approach like this: <svg> <svg:g skick-back-drop-item /> </svg> where "skick-back-drop-item" is the s ...

Maintaining the order of the returned values type is crucial when working with mapped objects in Typescript

Currently, I am developing a basic mapper function for objects. This function is designed to take an array of object properties and then return an array containing the corresponding values of these properties. The function works as intended; however, I hav ...

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

Unresponsive display on both 'Ionic development application' and 'physical mobile device'

As a newbie to Ionic, I recently delved into the world of Ionic 4 by following the guidance provided in the Ionic 4 documentation. After setting up my project using ionic start myApp sidemenu --type=angular, I noticed that everything ran smoothly on my bro ...

If a generic string argument is not specified as a string literal, it will not be narrowed unless it is the first argument

When the following code is executed, it works as intended and we can see that the arg variable is a string literal: const foo = <T extends string = string>(arg: T) => {}; foo('my string'); // const foo: <"my string">(arg ...

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

What is the best way to compare dates in order to obtain the necessary results?

Question : Filter the JSON array to retrieve specific entries 1: All entries with name "Sam". 2: All entries with date "Dec 2019". // JSON Data provided below. var data = [{ "id":"27", "0":{ "name":"Sam", "date":"2021-02-28" ...

Guide to encapsulating a container within a map function using a condition in JSX and TypeScript

Currently, I am working with an array of objects that are being processed by a .map() function. Within this process, I have a specific condition in mind - if the index of the object is greater than 1, it should be enclosed within a div element with a parti ...

Creating numerous bar graphs for each specific date

I have a dataset containing dates and corresponding information for each element. Despite trying various approaches, I am unable to create a barchart. Every solution I've attempted has been unsuccessful thus far. The dataset is structured as follows ...

Is there a way to retrieve the chosen value from a select element?

How do I retrieve the chosen value from a select element? In my select.component.ts file: export class PfSelectComponent implements OnInit { constructor() { } ngOnInit() { } @Input() options : Array<Object>; } Contents of select.compon ...

What could be the reason for the inconsistent behavior of onClick, causing it to occasionally fail to display the associated

I just started using typescript 2 days ago, mainly to create a custom component for my streamlit app. I've made a navigation bar with a tab that can be clicked on the sidebar, but it's displaying some erratic behavior. Sometimes when I click on t ...

Avoid using <input oninput="this.value = this.value.toUpperCase()" /> as it should not convert the text displayed on the "UI", rather it should send the uppercase value

<input oninput="this.value = this.value.toUpperCase()" type="text" id="roleName" name="roleName" class="form-control width200px" [(ngModel)]="role.roleName"> Even though the UI is changing ...

Managing state in NGRX entities can be simplified by learning how to assign action.payload to a state property in Ups

In the entity state, I have a reducer that needs to assign action.payload.Message to saveMessage.msg when carrying out upsertOne on the UPSERT_Message_SUCCESS action. export interface MessageState extends EntityState<Message> { // additional enti ...

The application of Angular's extension may experience functionality issues due to a failed ngcc operation

https://i.stack.imgur.com/Q7eFX.png The current issue I am encountering. https://i.stack.imgur.com/Kj1r0.png However, the command ng serve is functioning smoothly without any errors. https://i.stack.imgur.com/0SluL.png I'm also facing this partic ...

Unwrapping the Angular ngForm Mystery: Resolving

I was attempting to retrieve values using ngOnInit and initializing the form with default values, but for some reason the form is returning as undefined. I also tried using patchValue, but since the form is undefined, it doesn't work. It's intere ...