An infinite number of data requests are initiated asynchronously within a loop

When using Angular with TypeScript, I have the following component class:

@Injectable()
@Component({
    selector: 'app-mycomponent',
    templateUrl: './mycomponent.component.html' 
})
export class MyComponent implements OnInit{
    public myList : any[] = [];
constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get("url").subscribe(result => {
      this.myList= result;
    }, error => console.log(error));
  }

  getSubitem(id){
    return this.http.get("url/"+id).subscribe(result => {
      return result;
    }, error => console.error(error));
  }
}

And here is the corresponding HTML snippet:


<table>
  <thead>
    <tr>
      <th>ID</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of myList">
      <td>{{item.id}}</td>
      <td>{{(getSubitem(item.id) | async)}}</td>
    </tr>
  </tbody>

After starting the app and navigating to that view, myList loads and displays correctly. However, the getSubitem function is being triggered infinitely, causing the browser to crash.

How can I ensure that getSubitem is only called once for each item in the MyList array and that the correct information is displayed?

Answer №1

The issue lies in the continuous update of the view, resulting in repeated calls to the getsubitem() function.

One possible solution for loading items asynchronously could be as follows:

Component:

@Injectable()
@Component({
    selector: 'app-mycomponent',
    templateUrl: './mycomponent.component.html' 
})
export class MyComponent implements OnInit{
    public myList : any[] = [];
    public subitems: Object = {};
constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get("url").subscribe(result => {
      this.myList= result;
      for(let item of this.myList){
        this.getSubitem(item.id);
      }
    }, error => console.log(error));
  }

  getSubitem(id){
    return this.http.get("url/"+id).subscribe(result => {
      this.subitems[id] = result;
    }, error => console.error(error));
  }
}

HTML:

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of myList">
      <td>{{item.id}}</td>
      <ng-container *ngFor="let subitem of subitems[item.id]">
      <td>{{subitem}}</td>
      </ng-container>
    </tr>
  </tbody>

Kindly verify if this approach suits your requirements.

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

Implementing typing for a module that exports an instance of a particular class

Attempting to create a .d.ts file for the foo-foo-mq module has presented some challenges. Following the documentation, a 'foo-foo-mq' folder was created within the 'typings' directory at the project's root. An index.d.ts file was ...

Incorporating an expansion panel within an Angular Material table row

I'm currently working on incorporating an expansion panel, possibly a new component, similar to the mat-accordion. This will allow for a detailed view to be displayed within a mat-table row upon clicking. To better illustrate this requirement, I have ...

Filtering based on the boolean value of a checkbox in Angular

I'm struggling to implement a boolean filter for my search results, separating users with financial debt from those without. I need some guidance on how to achieve this. Data Filter @Pipe({ name: 'filter' }) export class FilterPipe implem ...

"Utilize TypeScript to create a function that can handle either a single value or

I am attempting to develop a double function with the following structure: type MaybeArray<T> = T | T[]; function double<T extends MaybeArray<number>>(data: T): T extends number[] ? number[] : number { if (Array.isArray(data)) { / ...

Leveraging Global Variables in TypeScript with Node Express

Having issues using global variables in node express when working with typescript. Specifically, trying to use the same global array variable tokenList:tokList across multiple modules and middleware, but haven't been successful so far. Any suggestions ...

Best practice in Angular 2: The difference between binding an object as a whole versus binding its individual

What is the best approach for a child component when dealing with object properties and change events? Example 1 <parent-component> <child-component [exampleInput]="object.val" (valueChanged)="updateObjectValue($event)"> ...

Enhance your social interactions by incorporating a custom interaction field using Google Analytics

At times, I have two share buttons in the user interface of my application (depending on the state). These buttons can share the same data but are located in different parts of the UI. The goal is to analyze from which button (part of UI) the share action ...

Avoid the occurrence of the parent's event on the child node

Attempting to make changes to an existing table created in react, the table is comprised of rows and cells structured as follows: <Table> <Row onClick={rowClickHandler}> <Cell onCLick={cellClickHandler} /> <Cell /> ...

Issues with Angular routing in Fuse administrator and user interfaces

I am encountering an issue with navigating routes for admin and user roles, where the user role has limitations compared to the admin role. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.1/angular.min.js"></script> const ...

The subscribe method in Angular TS may be marked as deprecated, but worry not as it is still

I have developed a function that retrieves new data from a service file each time it is called. Here is how the function looks: onCarChange() { this.carService.getCarData(this.selectedCar).subscribe( async (response: CarData) => { if (response?.d ...

Can the contents of a JSON file be uploaded using a file upload feature in Angular 6 and read without the need to communicate with an API?

Looking to upload a JSON file via file upload in Angular (using version 6) and read its contents directly within the app, without sending it to an API first. Have been searching for ways to achieve this without success, as most results are geared towards ...

The function Sync in the cp method of fs.default is not a valid function

When attempting to install TurboRepo, I encountered an issue after selecting npm. >>> TURBOREPO >>> Welcome to Turborepo! Let's get you set up with a new codebase. ? Where would you like to create your turborepo? ./my-turborepo ...

"Protractor encountered an issue when navigating to the most up-to-date Angular section in our

We are in the process of upgrading our application from AngularJS to the latest version of Angular. I am currently working on writing tests that transition from the AngularJS version of the app to the admin application, which is built using the latest ver ...

What methods can be used to test included content in Angular?

When testing an Angular component that includes transclusion slots utilizing <ng-content>, it becomes challenging to verify if the transcluded content is correctly placed within the component. For instance: // base-button.component.ts @Component({ ...

Experience the mesmerizing motion of a D3.js Bar Chart as it ascends from the bottom to the top. Feel free to

Here is the snippet of code I am working with. Please check the link for the output graph demonstration. [Click here to view the output graph demo][1] (The current animation in the output is from top to bottom) I want to animate the bars from Bottom to ...

Finding items in the database using their identification numbers

I have a scenario where I am accepting a list of IDs in my request, for example [1,2,3]. How can I use typeorm and querybuilder to retrieve only objects with these IDs from my database? I attempted the following: if(dto.customersIds){ Array.prototype. ...

Offering a limited selection of generic type options in TypeScript

Is there a shorthand in TypeScript for specifying only some optional types for generic types? For example, let's say I have a class with optional types: class GenericClass<A extends Type1 = Type1, B extends Type2 = Type2, C extends Type3 = Type3> ...

Querying Firebase to find documents that do not have a specific requested field present in all

My current project is using firebase. I am currently working on retrieving documents from firebase, but I have encountered a specific issue. The problem lies in the fact that I have older documents without a "hidden" field and newer documents with this fie ...

Using Html to differentiate input based on type

Looking for input on the code snippet below: <table class="details-table" *ngIf="animal && animaldata"> <tr *ngFor="let attribute of animaldata.Attributes"> <td class="details-property">{{ attribute.AttributeLabel }}& ...

Angular 4 Error: Missing Provider for CustomPipe

I have a unique custom decimal format pipe that utilizes the Angular Decimal pipe as well. This specific pipe is a crucial component of the shared module within my application. However, upon running the application in the feature module, I encounter an err ...