1

I have this ngFor:

<ion-card *ngFor="let review of reviews">
    <ion-card-content>
        {{getUserName(review.user_ID)}}
    </ion-card-content>
</ion-card>

I need to show the user name, but to get user name I need to call user service to get the username. The problem is when I try this. The page keeps loading and loading. What is the correct way to call service inside ngFor?

This is my getUserName method:

 getUserName(userId) {
     this.userService.loadUserById(userId)
        .then(dataUser => {
          this.user = dataUser;
        });

     return this.user; 
 }

And when I get the object how to access the object property like in HTML? (Example: user.firstName). Thanks.

Raulucco
  • 3,406
  • 1
  • 21
  • 27
Stevanus W
  • 115
  • 3
  • 12

1 Answers1

1

You would at least need some cache to not call out to the server for every change detection cycle, which is when getUsername(review.uer_ID) is called like for example explained in What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?

A better way would be to fetch all usernames for all reviews in advance and make them available as array you bind to inside *ngFor.

Calling methods that are expensive or have side effects from templates is strongly discouraged because it is extremly inefficient.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567