Currently, I am working with Angular and Material-Angular to display data from the Reqres API (https://reqres.in). Despite building a table with pagination, I encountered an issue with my pagination functionality not working as expected.
To manage the data retrieval and storage, I have set up a service and model using HttpClient. Within the component class, I have defined two variables for this purpose: users: User[]
and
dataSource = new MatTableDataSource<User>(this.user)
.
import { Component, OnInit, ViewChild } from '@angular/core';
import { User } from '../config/user.module';
import { DataService } from '../data.service';
import { MatPaginator, MatTableDataSource } from '@angular/material';
@Component({
selector: 'app-users-list',
templateUrl: './users-list.component.html',
styleUrls: ['./users-list.component.sass']
})
export class UsersListComponent implements OnInit {
users: User[];
page: number;
displayedColumns = ['Id', 'FirstName'];
dataSource = new MatTableDataSource<User>(this.users);
constructor(private dataService: DataService) { }
@ViewChild(MatPaginator) paginator: MatPaginator;
ngOnInit() {
this.dataSource.paginator = this.paginator;
this.showUsers();
}
showUsers() {
this.page = 1;
this.dataService.getUsers(this.page)
.subscribe(res => {
this.users = res['data'];
});
}
}
In terms of the template.html file:
<section class="list">
<table mat-table [dataSource]="users" class="mat-elevation-z8 table">
<ng-container matColumnDef="Id">
<th mat-header-cell *matHeaderCellDef>
<span class="table-header">No.</span>
</th>
<td mat-cell *matCellDef="let user">
<span class="table-value">{{user.id}}</span>
</td>
</ng-container>
<ng-container matColumnDef="FirstName">
<th mat-header-cell *matHeaderCellDef>
<span class="table-header">Name</span>
</th>
<td mat-cell *matCellDef="let user">
<span class="table-value">{{user.first_name}}</span>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator [pageSizeOptions]="[3]" showFirstLastButtons></mat-paginator>
</section>
Upon changing users
to dataSource
in the HTML file:
<table mat-table [dataSource]="HERE" class="mat-elevation-z8 table">
, no results are displayed in the table. It seems like the declaration of dataSource
is correct and it should fetch data from users
, but that's not happening. If I switch back to using users
, everything displays correctly, yet I require dataSource
for pagination purposes. Could it be that the issue lies with the timing of when data is present in users
during invocation?
Current Setup: Angular-CLI 7