Page making too many HTTP Requests


#1

This is my .ts code

 userCount(event_id){
    this.http.get('http://localhost/getCount.php?event_id='+event_id)
      .subscribe(res=>{
        this.eventUserCount = res.json();
        console.log("User NUM :: ", this.eventUserCount) 
        return this.eventUserCount
      });

  }

this is the HTML code from where there above function is being called:

<div *ngFor="let event of events">
....    
<ion-col col-6 center text-center>
    <button  ion-button>
        <div> {{ userCount(event.event_id) }} Users</div>
    </button>
</ion-col>
...
</div>

I am getting infinite response from the server(as seen from console.log) I want to make separate http request for every list item and show the count for every event , instead of this infinite request and response loop. Can anyone help me with this??


#2

You’re trying to do too much work in the template again.

events must get populated somehow. Whenever it is that that happens is when you should be getting the user counts. What I would do is to simply put it into each member of events, which makes the template simple and natural. Something like this:

this.http.get(url).map(rsp => rsp.json())
  .subscribe((events) => {
    this.events = events;
    this.fetchUserCounts();
  });

fetchUserCounts(): void {
  this.events.forEach((evt) => {
    this.http.get('getCount' + evt.id).subscribe(nusers => evt.nusers = nusers);
  });
}

Then you just have to say {{event.nusers}} in the template.