The Dead Man
The Dead Man

Reputation: 5556

How to add counter in angular 6?

I have a function which grabs comments from the server, I would like to display total number of comments available in a server.

Here is the function in .ts file:

 this.activeRouter.params.subscribe(params => {
   // tslint:disable-next-line:prefer-const
   let id = params['id'];
   this.userService.getComments(id)
     .pipe(
       map(data => data.sort((a, b) => new Date(b.localTime).getTime() - new Date(a.localTime).getTime()))
      )
      .subscribe(data => this.comments = data);
});

Here is the get function in service

  getComments (id: number) {
    return this.http.get<Comment[]>(this.commentsUrl);
  }

Here is the html for displaying comments

 <div class="comments-description" *ngFor="let comment of comments">
        <span class="comments_count">(353)</span>
      <div class="comments-photo">
        <img src="https://randomuser.me/api/portraits/men/84.jpg" alt="">
      </div>
      <div class="comments_wrapper">
        <div class="comments_details">
          <h1>{{comment.author}}</h1>
          <span class="days">1d</span>
        </div>
        <div class="comments_text">
          <p>{{comment.description}} </p>
        </div>
      </div>
    </div>

Upvotes: 1

Views: 3902

Answers (5)

Sunil Game
Sunil Game

Reputation: 29

Update your API and get comments count using API and show your comment count.

Upvotes: 1

user6299088
user6299088

Reputation:

Solution:

While getting comments data from server , You have to return total number of comments along with the new data.

Once you call service you can add data in one array. and set total count in one variable.

Note: You have to read count from sever and return result in same API or service

Upvotes: 2

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

If you get all the comments in the response then you can use comments.length

<span class="comments_count">{{comments.length}}</span>

But the best practice is to get it from the API side. Add one more field in your API response for comment count.

Upvotes: 2

Eugene Mihaylin
Eugene Mihaylin

Reputation: 1776

Such counter must be on the server side.

For example, post has 10000 comments.

1 request will not fetch them all, only a portion (page).

And it's not good to get them all only to find out a count.

So the response should contain a 'count' field.

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

why not simply use the length

<span class="comments_count">{{comments.length}}</span>

Upvotes: 3

Related Questions