Get request getting into an infinite loop

I have a rather long question but I think it may be trivial issue. I have some data stored in my MySQL back end. I am using PHP to fetch the data is display in in my view. My setup is simple. I have a restaurant and likes table. So for each restaurant I want to display its like count. My approach is below.

In my service.ts file, I have a simple function that gets to a php URL.

 getLikes(id){
    return this.http.get(this.LIKECOMMENTHANDLER);
 }

In my component.module.ts file, I used the above function and simply log the response

getLikesCount(id){
    //console.log("my id "+id);
    this.restaurantInfo.getLikes(id).subscribe(
      (response)=> {console.log(response)},
      (error) => console.log(error)
    );
  }

I called the above function in my template.html file as follows.


<ion-card *ngFor="let restaurant of restaurants" (click)="navigateToRestaurantDetailsPage('RestaurantDetailsPage', restaurant)">
  //display restaurant information here then
   <ion-col>
   <button ion-button icon-left clear small>
    <ion-icon name="thumbs-up"></ion-icon>
    <div>{‌{getLikesCount(restaurant.id)}}</div>
   </button>
  </ion-col>
</ion-card>

The code keeps running and never stops and it creates a memory leak.

Don’t do this. Move it to a (click) handler on the button instead.

Like @rapropos said, don’t do this.

You can only do this when the getLikesCount() is syncronous and doesn’t take a lot of time, but it still is bad practice.

@rapropos, I understand your point, but I just want to display value upon page load and not when a button is clicked. Is this not possible?

Then call getLikesCount in a lifecycle event such as ionViewDidLoad(), store the result in a controller property, and reference that from the template.

The getLikesCount has a parameter called id, which is only accessible in the template. I don’t seems to find a way of accessing this in the .ts file.

I think you have a design problem with your API. Instead of firing so many HTTP requests, simply add the like count to each Restaurant that comes from the server, and then it will be easily available in the template as {{restaurant.likeCount}}.

Yes you are right, I have just started looking at this, I will change the design as you have suggested.

@rapropos, thanks for the pointer. I am now doing it as you have suggested.

just remove the enclosing paranthesis ‘{{}}’, pass it as a plain variable

<ion-card *ngFor=“let item of data” (click)=“gotoEvent(item.HostName)”>

{{item.UserName}}