角材料-解决路线后分页不起作用

时间:2019-01-16 07:23:37

标签: angular routes angular-material resolver

我正在使用angular-material 2来制作桌子。我遇到的情况是我在页面加载之前解析数据,它可以正常工作,但问题是在那之后分页不起作用。

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'
      }
    }
  ]
}];

我已经创建了一个名为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);
    }
  }
}

这是我的组件文件,我正在其中接收从服务器返回的数据。

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;
    });
  }

现在,我以前在getNewRequests中手动调用ngAfterViewInit函数,因为我没有解析数据。像这样

 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);
                },


      )
      }

在我看来,我也有一个搜索字段,可以在其中搜索关键字等。现在如何使分页有效?

1 个答案:

答案 0 :(得分:0)

只需按如下所示在Table和Mat-Paginator中进行更改,以按如下所示调用函数getNewRequests():

<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>