[Fixed] function inside a ngFor loop calls infinitely

Issue

function
this function returns the username for each order.

I am calling this function here in my component.html where for each order ngFor loop runs. ngFor looping
this keeps looping and calling api infinitely. I would really appriciate any suggestions. Thank you.

Solution

There are multiple issues here.

  • Please DO NOT post the code as images.
    • You are now expecting people to type in your code for replicating the issue.
    • If the external image host goes down your question is rendered useless.
  • You cannot return anything from a subscription. You are passing callbacks to the subscribe() function and they cannot return anything.
  • Calling a function in template interpolation {{ }} or data-binding []=() w/ default change detection strategy would trigger the function for each change detection cycle ergo "infinite" calls.

You either need to get all the info in the controller (*.ts) or use async pipe in the template.

  • Use forkJoin with Array#map to fetch the data for all orders in parallel.

Controller (*.ts)

ngOnInit() { // <-- or wherever the `dataArray` is initialized
  forkJoin(
    this.dataArray.map(order => 
      getuserdata(order.user_id).pipe(
        map(data => ({
          ...order,
          data: data
        }))
      )
    )
  ).subscribe({
    next: (array: any) => this.dataArray = array,
    error: (error: any) => { /* handle error */ }
  });
}

getuserdata(userid) {
  const userId = { params: { id: userid }};
  return this._order.getUserdata(userId).pipe(
    map(res => {
      this.userData = res;
      return res.userdata.fullname
    })
  );
}

Template (*.html)

<td>{{ order.data }}</td>

Leave a Reply

(*) Required, Your email will not be published