3

I need to implement a server pagination for a table where the data is taken from an SQL Database and i need to save the data from the response as a number(count:number) but if i check the totalItems in consolelog the value is undefined.

If i change the totalItems to 100, everything works almost perfectly except that it dont displays the corect number of pages.

The return value of GET method is only that number. So i have to take that number and put it in count:number or return that number as a value from typescript method.

component.ts

count:number;

constructor(
    private service: UserService

  ) {
    this.config = {
      itemsPerPage: 10,
      currentPage: 1,
      totalItems : this.service.getPaginationInfo()
    };
   }

service.ts

getPaginationInfo() {
    this.http.get(this.BaseURL + '/Count?id=' + this.userIdString)
    .subscribe(result => {
     this.count = result as number},
     (err) => {
       console.log(err);
     }

     );

    return this.count;
  }

ASP .NET Core method:

[HttpGet]
        public int GetContactCount(string id)
        {

            return _context.ContactDetails.Count(w => w.UserId == id);

        }

Get method return this:

30

HTML:

<table class="table table-hover text-white transparent-dark">
    <tr *ngFor="let contact of service.list | paginate: config">
      <td data-toggle="modal" data-target="#UpdateContactModal" (click)="populateForm(contact)">{{contact.Name}}</td>
      <td data-toggle="modal" data-target="#UpdateContactModal" (click)="populateForm(contact)">{{contact.PhoneNumber}}
      </td>
      <td>
        <i class="far fa-trash-alt fa-lg text-danger" (click)="this.service.onDelete(contact.ContactId)"></i>
      </td>
    </tr>
  </table>
  <pagination-controls (pageChange)="pageChanged($event)" class="center-footer text-white"></pagination-controls>
Eduard
  • 83
  • 6

1 Answers1

1

Your getPaginationInfo() is an async function. You can't return a simple number type.

To fix that issue, change the service to return an Observable<number>:

  getPaginationInfo() {
    return this.http.get<number>(this.BaseURL + '/Count?id=' + this.userIdString);
    .subscribe(
      result => { this.count = result as number},
      (err) => { console.log(err); }
     );
    return this.count;
  }

And change the invocation in the following way:

this.config = {
  itemsPerPage: 10,
  currentPage: 1,
  totalItems : 0
};

this.service.getPaginationInfo().subscribe(
    result => { 
      this.config.totalItems = result;
    },
    (err) => { console.log(err); }
);
itminus
  • 23,772
  • 2
  • 53
  • 88