Get request getting into an infinite loop


#1

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.


#2

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


#3

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.


#4

@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?


#5

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


#6

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.


#7

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}}.


#8

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


#9

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


#10

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

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

{{item.UserName}}