Пагинация матовой таблицы не загружается правильно

В настоящее время все результаты объекта JSON отображаются на первой странице, поэтому разбивка на страницы не работает. Таблица матов не перестанет расти в высоту, когда достигнет 10 строк и начнет разбиваться на страницы. Я ссылался на документацию и примеры, но не могу заставить его перестать расти в высоту и начать перемещать строки на следующую страницу. Также мат-сортировка не работает. Не уверен, связано ли это. Я ценю любую помощь.


  <table mat-table class="full-width-table" [dataSource]="dataSource" matSort aria-label="Elements">
          <!-- Id Column -->
          <ng-container matColumnDef="title">
            <th class="tableStyle" mat-header-cell *matHeaderCellDef mat-sort-header>Title</th>
            <td [ngStyle]="{'width': '20%'}" class="tableStyle" mat-cell *matCellDef="let row">
              {{row.title}}</td>
          </ng-container>


          <ng-container class="tableStyle" matColumnDef="lastBidderName">
            <th id="dateReceivedHeader" class="tableStyle" mat-header-cell *matHeaderCellDef mat-sort-header>Last Bidder
            </th>
            <td [ngStyle]="{'width': '20%'}" id="dateReceived" class="tableStyle" mat-cell *matCellDef="let row">
              {{row.lastBidderName }}</td>
          </ng-container>

          <ng-container class="tableStyle" matColumnDef="currentBid">
            <th id="dateReceivedHeader" class="tableStyle" mat-header-cell *matHeaderCellDef mat-sort-header>Last Bid
            </th>
            <td [ngStyle]="{'width': '15%'}" id="dateReceived" class="tableStyle" mat-cell *matCellDef="let row">
              ${{row.currentBid }}</td>
          </ng-container>

          <ng-container class="tableStyle" matColumnDef="auctionType">
            <th id="dateReceivedHeader" class="tableStyle" mat-header-cell *matHeaderCellDef mat-sort-header>Auction
              Type</th>
            <td [ngStyle]="{'width': '20%'}" id="dateReceived" value="returnAuctionType(row.auctionType)"
              class="tableStyle" mat-cell *matCellDef="let row">
              {{returnAuctionType(row.auctionType)}}</td>
          </ng-container>

          <ng-container class="tableStyle" matColumnDef="auctionEndDateTime">
            <th id="dateReceivedHeader" class="tableStyle" mat-header-cell *matHeaderCellDef mat-sort-header>Auction End
              Date</th>
            <td [ngStyle]="{'width': '55%'}" id="dateReceived" class="tableStyle" mat-cell *matCellDef="let row">
              <span id="endDateTimeLabel" [ngClass]="{'activeAuction': row.auctionEndDateTime > this.today}">
                {{row.auctionEndDateTime * 1000 | date: 'medium'}}</span></td>
          </ng-container>


          <tr mat-header-row *matHeaderRowDef="displayedColumnAuctions"></tr>
          <tr mat-row *matRowDef="let row; columns: displayedColumnAuctions;"></tr>

        </table>

        <mat-paginator id="paginator" #paginator [length]="dataSource?.data.length" [pageIndex]="0" [pageSize]="10">
        </mat-paginator>



файл mat-table.ts


 dataSource: MatTableDataSource<Listing>;

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
  @ViewChild(MatSort, {static: true}) sort: MatSort;

  displayedColumnAuctions = [
    "title",
    "lastBidderName",
    "currentBid",
    "auctionType",
    "auctionEndDateTime"
  ];
  constructor(
    private mobileDetect: DeviceDetectorService,
    private submitListingService: SubmitListingService,
    private authService: AuthService
  ) {}

  ngOnInit() {


    this.userId = this.authService.getUserId();
    this.submitListingService.getArtistListings(this.userId).subscribe(res => {
      console.log("res");
      console.log(res);
      this.auctions = res.posts;
      this.auctions.sort((a, b) => b.auctionEndDateTime - a.auctionEndDateTime);
      this.dataSource = new MatTableDataSource(this.auctions);
      this.dataSource.sort = this.sort;
    });
  }
  ngViewAfterInit() {
    this.dataSource.paginator = this.paginator;
  }
  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }



person user6680    schedule 01.01.2020    source источник


Ответы (1)


У вас есть проблема asyc, вы определяете источник данных при получении ответа от сервера, но вы определяете разбиение на страницы в жизненном цикле ngViewAfterInit.

Пожалуйста, измените свой код примерно так

dataSource: MatTableDataSource<Listing> = new MatTableDataSource();
itemsCount = 0;

ngOnInit() {
   this.dataSource.paginator = this.paginator;
   this.dataSource.sort = this.sort;
   this.submitListingService.getArtistListings(this.userId).subscribe(res => {
      console.log("res");
      console.log(res);
      this.auctions = res.posts;
      this.auctions.sort((a, b) => b.auctionEndDateTime - a.auctionEndDateTime);
      this.dataSource.data = this.auctions;
   });
}

person Ashot Aleqsanyan    schedule 01.01.2020
comment
Я обновил свой код, чтобы отразить ваши изменения. Я удалил [length]="dataSource?.data.length" [pageIndex]="0" и обновил ngOnInit, но проблема все еще сохраняется. pastebin.com/qkiD302d Он запускается из div и выглядит так. postimg.cc/mtfPH0bb - person user6680; 02.01.2020
comment
@ user6680, не могли бы вы проверить пример stackblitz stackblitz.com/edit/angular-ykerxt - person Ashot Aleqsanyan; 02.01.2020
comment
Я избавился от ngViewAfterInit и добавил ваш код, но у меня все еще проблема, которую вы видите на изображении, которое я опубликовал в последнем комментарии. Вот мой обновленный код. pastebin.com/ZgDefu3F - person user6680; 02.01.2020
comment
@ user6680 вы проверили пример stackblitz? Не могли бы вы сравнить свой пример с примером stackblitz. это очень странно, на вашем примере все выглядит хорошо. - person Ashot Aleqsanyan; 02.01.2020
comment
Единственное, что я вижу по-другому, - это то, как служба настроена и используется sort: string, order: string, page: number Вот пример функции, вызываемой из службы pastebin. com / ZCUp1JcZ Я предполагаю, что это связано, но я думаю, я не знаю, как интегрировать эту часть, если это проблема - person user6680; 02.01.2020
comment
@ user6680 Думаю, это не имеет значения. - person Ashot Aleqsanyan; 02.01.2020
comment
@ user6680 что такое maxPosts из ответа сервера? - person Ashot Aleqsanyan; 02.01.2020
comment
Давайте продолжим это обсуждение в чате. - person Ashot Aleqsanyan; 02.01.2020