CS_student
CS_student

Reputation: 107

Angular inifinite loop calling function

In a few Angular projects I have the same problem, whenever I try to call a function inside my HTML (that retrieves some value from the api) it triggers an infinite loop. In the example below it's getUser() that triggers the loop.

HTML

<ul>
    <li *ngFor="let order of orders">
        {{ getUser(order.orderNr).emailAddress }}
    </li>
</ul>

component

private getOrdersList() {

    this.orderService.getAll().subscribe(
        orders => {
            this.orders = orders;
        }
    );
}

public getUser(orderNr: number) {
    return this.orderService.getUser(orderNr);
}

service

public getAll(): Observable<Order[]> {
    return this.api.get<Order[]>('orders');
}

public getUser(orderNr: number) {
    return this.api.get<void>('orders/'+orderNr);
}

I think it has something to do with the way Angular handles data but I'm fairly new to Angular and unsure how to retrieve this data without causing the loop. Perhaps someone more experienced can provide some help?

Upvotes: 1

Views: 3451

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657731

It's not an infinite loop, it's just Angulars change detection.

In development each change detection run also follows a 2nd turn. Change detection is run when any async call completes (event handlers, timeout, ...) and can therefore happen quite often.

Binding to functions in the view should generally be avoided, instead assign the result to a field and bind to that field instead. Angular is extremely efficient checking whether field values have changed.

Upvotes: 3

Related Questions