Usman Iqbal
Usman Iqbal

Reputation: 2429

Angular Material - pagination not working after resolving route

I am using angular-material 2 to make tables. I have a case in which I am resolving data before page loads, It works fine but the problem is pagination is not working after that.

drivers-routing.module.ts

const routes: Routes = [{
  path: '',
  component: MainListingComponent,
  children: [

    {
      path: 'new-requests',
      component: NewRequestsComponent,
      resolve: {
        resolvedData: RouteResolverService
      },
      data: {
        apiUrl: Globals.urls.driver.getDrivers,
        params: {
          offset: 0,
          limit: 10,
          newRequests: true,
          isComplete: 2
        },
        methodType: 'POST'
      }
    }
  ]
}];

I have created a service called RouteResolverService

route-resolver.service.ts

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { HttpService } from './http-service';
@Injectable({
  providedIn: 'root'
})
export class RouteResolverService {

  constructor(private httpService: HttpService) { }

  resolve (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
    const url = route.data['apiUrl'];
    const methodType = route.data['methodType'];
    const params = route.data['params'];

    console.log(params)
    if (methodType === 'GET') {
      return this.httpService.getRequest(url, params, false);
    } else if (methodType === 'POST') {
      return this.httpService.postRequest(url, params, false);
    } else if (methodType === 'PUT') {
      return this.httpService.putRequest(url, params, false);
    } else if (methodType === 'DELETE') {
      return this.httpService.deleteRequest(url, params, false);
    }
  }
}

This is my components file in which i am receiving data being return from server.

new-requests.component.ts

constructor(public service: HttpService, public toastr: ToastrService, private route: ActivatedRoute) {
    this.route.data.subscribe(data => {
      this.dataSource = data['resolvedData'].data.drivers
      this.isLoadingResults = false;
      this.resultsLength = data['resolvedData'].data.count;
      this.totalRecords = this.dataSource ? this.dataSource.length : 0;
    });
  }

Now previously I was manually calling getNewRequests function in ngAfterViewInit as I was not resolving data. Like this

 ngAfterViewInit() {
            this.httpSearch$ = fromEvent(this.input.nativeElement, 'keyup')
              .pipe(
                debounceTime(400),
                distinctUntilChanged(),
                tap(() => {
                  this.paginator.pageIndex = 0;
                  this.search({ searchText: this.input.nativeElement.value });
                })
              )
              .subscribe();

            // this.getNewRequests(this.isComplete); I COMMENTED OUT THIS LINE AFTER RESOLVING DATA
          }

          getNewRequests(type) {
            this.httpSub$ = this.paginator.page
              .pipe(
                startWith({}),
                switchMap(() => {
                  let params = {
                    offset: ((this.paginator.pageIndex + 1) * this.paginator.pageSize) - this.paginator.pageSize,
                    limit: this.paginator.pageSize,
                    newRequests: true,
                    isComplete: this.isComplete    //1 for complete , 0 for incomplete, for all : 2
                  };
                  this.isLoadingResults = true;
                  return this.service.postRequest(this.globals.urls.driver.getDrivers, params);
                }),
                map(res => {
                  return res.data;
                }),
              ).subscribe(
                data => {
                  this.isLoadingResults = false;
                  this.resultsLength = data.count;
                  this.dataSource = data.drivers;
                  this.totalRecords = data ? data.drivers.length : 0;
                },
                err => {
                  this.dataSource = [];
                  this.isLoadingResults = false;
                  // this.service.showError(err.error.message);
                }
              );
          }

          search(input) {
            this.isLoadingResults = true;
            const params = {
              searchText: input.searchText || null,
              newRequests: true,
              isComplete: this.isComplete
            };
            this.service.postRequest(this.globals.urls.driver.getDrivers, params)
              .pipe(
                map(res => {
                  return res.data;
                })
              )
              .subscribe(
                data => {
                  this.isLoadingResults = false;
                  this.resultsLength = data.count;
                  this.dataSource = data.drivers;
                  this.totalRecords = data ? data.drivers.length : 0;
                },
                err => {
                  this.dataSource = [];
                  this.isLoadingResults = false;
                  // this.service.showError(err.error.message);
                },


      )
      }

i have a search field too, in my view, where I search keyword etc. Now How can I make the pagination work ?

Upvotes: 0

Views: 1213

Answers (1)

Mahesh Jarange
Mahesh Jarange

Reputation: 11

Just make the changes in your Table and Mat-Paginator as below to call the function getNewRequests() as below:

<table mat-table [dataSource]="dataSource" class="table" matSort matSortActive="CourseName" (matSortChange)="getNewRequests()" matSortDisableClear matSortDirection="asc"></table>

<mat-paginator [length]="resultsLength" [pageSize]="10" [pageSizeOptions]="[10,50,100]" (page)="getNewRequests()" showFirstLastButtons></mat-paginator>   

Upvotes: 1

Related Questions