0

Getting an infinite loop trying iterate through the promise resulting from this function call:

 public CUSTOMERS = [
    {"id":1,"name":"Crypto Joe", "description":"Love Crypto in the Morning"},
    {"id":1,"name":"Crypto Sue", "description":"Love Crypto in the Evening"}
];

    loadCustomers():Promise<any[]> {
      return of(this.CUSTOMERS).toPromise()
    }

And this is the template:

<li *ngFor="let customer of loadCustomers() | async">
    <h3>{{customer.name}}</h3>
    <code> {{customer.description}} </code>
</li>
</ul>

Thoughts? This is a stackblitz demo:

https://stackblitz.com/edit/minimal-angular-ngfor-loop

I updated the demo to use changeDetection: ChangeDetectionStrategy.OnPush but it still results in an infinite loop. Perhaps this can only be done with observables?

Ole
  • 41,793
  • 59
  • 191
  • 359
  • 1
    Does this answer your question? [angular2 - infinite loop when i call method from a Angular 2 class inside template](https://stackoverflow.com/questions/43081810/angular2-infinite-loop-when-i-call-method-from-a-angular-2-class-inside-templa) – jonrsharpe Mar 30 '20 at 06:40
  • Also considering you consume the `Promise` via `async` pipe you might as well just provide an observable (`return of(this.CUSTOMERS);`). The `async` pipe handles this just as fine. – Philipp Meissner Mar 30 '20 at 06:56
  • I changed the original demo to use ` changeDetection: ChangeDetectionStrategy.OnPush ` but it does not work. Any idea why? – Ole Mar 30 '20 at 07:04
  • 1
    https://stackoverflow.com/questions/43081810/angular2-infinite-loop-when-i-call-method-from-a-angular-2-class-inside-templa#comment73324153_43122416 – jonrsharpe Mar 30 '20 at 07:13

1 Answers1

1

The Problem is the change detection. So as soon as the first customer is added to the DOM angular detects the change and recalls loadCustomers() which results in a infinite loop.

Either change detection to "OnPush" or bind to a property instead of a method or getter.

Jazjef
  • 461
  • 3
  • 10
  • Cool - Binding the property works: https://stackblitz.com/edit/minimal-angular-ngfor-loop-with-promise – Ole Mar 30 '20 at 07:01
  • I changed the original demo to use ` changeDetection: ChangeDetectionStrategy.OnPush ` but it does not work. Any idea why? – Ole Mar 30 '20 at 07:04
  • 1
    As Philipp Meissner already mentioned consider using observable instead of promise. so you simply use of(this.CUSTOMERS) and the property will be of type customer$: Observable. Glad i could help – Jazjef Mar 30 '20 at 07:05
  • 1
    I you want to use change detection you would manually have to trigger the change detection. Inject ChangeDetectorRef in the constructor and call changeDetection.detectChanges(). This triggers the render anew – Jazjef Mar 30 '20 at 07:06