Issues data binding to a method with an *ngFor variable as a parameter


#1

The console will continue logging data. The getAvatar method is being called over and over. Is there an alternative to the code I have below?

users.ts

...
  getAvatar(mediaId) {
    let mediaQuery = "?parent=" + mediaId;
    this.wpService.getMedia(mediaQuery).then((mediaData) => {
      //console.log(mediaData[0].source_url);
      return mediaData[0].source_url;
    });
  }
...

users.html

...
    <ion-item *ngFor="let aPerson of persons">
      <ion-avatar item-start>
        <img src="{{getAvatar(aPerson.id)}}">
      </ion-avatar>
...

#2

What I would do is add an avatar property to each Person, and populate it as rarely as you can (probably only once). Then you just can say <img [src]="aPerson.avatar">.


#3

Persons refers to data returned from a get request to a wordpress site for “persons”. This return data does not have a link to the avatar. Instead it has a “featured_media” id with which I must make a separate api call for the media return data. From there I use the source_url property to get the avatar link.

Binding to the getAvatar method was my attempt to plug *nFor data to get a media link for each iteration from a different api call.


#4

I get that, but you want to be doing that on your schedule, and presumably you can fire off each one of those requests for each person once the list of people comes back, and simply assign the result to an “avatar” property that you add locally.

It’s a bad idea, because as you noticed, Angular’s change detection calls any functions in template expressions a lot.


#5

Thank you. That is a much better way to think about it. I got something working.