Mat Table 的 Mat Paginator 无法处理 api 数据 [英] Mat Paginator of Mat Tabledoesn't work with api data

查看:18
本文介绍了Mat Table 的 Mat Paginator 无法处理 api 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过类似的问题,但似乎对我没有任何作用.我有一个 mat 表,我在其中显示来自 api 的数据.但我不知道如何遍历数据源".下面是我的代码,以及我在检查控制台日志时如何获取数据..ts 文件

import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';从'../../models/pokemon'导入{Pokemon, PokemonData};从'../../models/services/pokemon.service'导入{PokemonService};从@angular/router"导入{ActivatedRoute};从@angular/material/table"导入 {MatTableDataSource};从'@angular/material/paginator'导入{MatPaginator};@成分({选择器:'app-pokemon',templateUrl: './pokemon.component.html',styleUrls: ['./pokemon.component.css']})导出类 PokemonComponent 实现 OnInit {公共口袋妖怪:口袋妖怪[];公共名称:字符串;公共网址:字符串;公共类型:字符串;扩展元素:PokemonData |空值;数据源 = 新的 MatTableDataSource();displayPokemonColumns: string[] = ['name', 'url', 'pokemonDetails'];@ViewChild(MatPaginator, {read: true}) 分页器:MatPaginator;//////tslint:disable-next-line:typedef//tslint:disable-next-line:typedef//ngAfterViewInit() {////this.dataSource.paginator = this.paginator;//////}构造函数(私有 pokemonService:PokemonService,私有路由:ActivatedRoute){}//函数(在下面调用)发出对 API 的调用.subscribes 显示返回的结果.将结果添加到显示数组onLoadPokemonList(): void {this.pokemonService.getPokemonList().subscribe(资源=>{//this.pokemon = JSON.parse(JSON.stringify(res));this.pokemon = res;this.dataSource.data = this.pokemon;setTimeout(() => {this.dataSource.paginator = this.paginator;});控制台日志(this.dataSource);});}ngOnInit(): 无效 {this.onLoadPokemonList();}}

html 文件

<h1 matColumnDef=title">POKEDEX</h1><table mat-table #table [dataSource]="dataSource";class =mat-elevation-z8"多模板数据行><!-- <table mat-table [dataSource]="pokemon.results";class =mat-elevation-z8"multiTemplateDataRows>--><ng-container matColumnDef="name"><th mat-h​​eader-cell *matHeaderCellDef>名称</th><!-- <td mat-cell *matCellDef=let res">{{res?.name}} </td>--><td mat-cell *matCellDef=let res">{{res.name}} </td></ng-容器><ng-container matColumnDef="url"><th mat-h​​eader-cell *matHeaderCellDef>URL</th><td mat-cell *matCellDef=let res">{{res.url}} </td></ng-容器><ng-container matColumnDef="pokemonDetails"><th mat-h​​eader-cell *matHeaderCellDef>口袋妖怪详情</th><td mat-cell *matCellDef=let res"><button mat-raised-button color="primary";routerLink="/pokemonData/{{res.name}}">Pokemon Details</button></td></ng-容器><tr mat-h​​eader-row *matHeaderRowDef="displayPokemonColumns;粘性:真"></tr><tr mat-row *matRowDef="let row;列:displayPokemonColumns;"类=示例元素行"[class.example-expanded-row]=expandedElement === row";(click)="expandedElement = expandElement === row ?null : row"></tr><mat-paginator #paginator[pageSize]=10"[pageSizeOptions]=[5, 10, 20]"></mat-paginator>

这是我得到的数据:

MatTableDataSource {_renderData: BehaviorSubject, _filter: BehaviorSubject, _internalPageChanges: Subject, _renderChangesSubscription: Subscriber, sortDataAccessor: ƒ, ...}filterPredicate: (data, filter) =>{…}filteredData: {count: 1050, next: "https://pokeapi.co/api/v2/pokemon?offset=150&limit=150", previous: null, results: Array(150)}sortData:(数据,排序)=>{…}sortingDataAccessor: (data, sortHeaderId) =>{…}_data:BehaviorSubject {_isScalar:false,观察者:Array(1),关闭:false,isStopped:false,hasError:false,…}_filter:BehaviorSubject {_isScalar:false,观察者:Array(1),关闭:false, isStopped: false, hasError: false, ...}_internalPageChanges: Subject {_isScalar: false, Observers: Array(0), closed: false, isStopped: false, hasError: false, ...}_paginator: undefined_renderChangesSubscription: Subscriber {closed: false,_parentOrParents: null, _subscriptions: Array(1), syncErrorValue: null, syncErrorThrown: false, ...}_renderData: BehaviorSubject {_isScalar: false, 观察者: Array(1), closed: false, isStopped: false, hasError: false, ...}数据:(...)过滤器:(...)分页器:(...)排序:(...)__proto__:数据源

我需要的数据在filteredData下.

当我这样做

我得到了正确的表,而不是 dataSource,但分页器(显然)不起作用.

解决方案

最终有效的是删除模板上的 *ngIf 条件.我在堆栈溢出时找到了这个解决方案.分页器现在工作正常.

I've seen similar questions, but nothing seems to work for me. I have a mat table where I display data from an api. But I don't know how to iterate through the 'dataSource'. Below is my code, and how I get the data when I check console log. ts file

import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {Pokemon, PokemonData} from '../../models/pokemon';
import {PokemonService} from '../../models/services/pokemon.service';
import {ActivatedRoute} from '@angular/router';
import {MatTableDataSource} from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';

@Component({
  selector: 'app-pokemon',
  templateUrl: './pokemon.component.html',
  styleUrls: ['./pokemon.component.css']
})
export class PokemonComponent implements OnInit {
  public pokemon: Pokemon[];
  public name: string;
  public url: string;
  public type: string;
  expandedElement: PokemonData | null;
  dataSource = new MatTableDataSource();
  displayPokemonColumns: string[] = ['name', 'url', 'pokemonDetails'];
  @ViewChild(MatPaginator, {read: true}) paginator: MatPaginator;
  //
  // // tslint:disable-next-line:typedef
  // tslint:disable-next-line:typedef
  // ngAfterViewInit() {
  //   // this.dataSource.paginator = this.paginator;
  // //
  // }

  constructor(private pokemonService: PokemonService, private route: ActivatedRoute) {
  }

  // function (which is called below)issues call to API. subscribes shows to the results that are returned. adds results to shows array
  onLoadPokemonList(): void {
  this.pokemonService.getPokemonList().subscribe(
    res => {
  // this.pokemon = JSON.parse(JSON.stringify(res));
  this.pokemon = res;
  this.dataSource.data = this.pokemon;
  setTimeout(() => {
        this.dataSource.paginator = this.paginator;

      });
  console.log(this.dataSource);
    });

  }


  ngOnInit(): void {
  this.onLoadPokemonList();

  }


}

html file

<div class="table"  *ngIf="pokemon">
  <h1 matColumnDef="title">POKEDEX</h1>
  <table mat-table #table [dataSource]="dataSource" class="mat-elevation-z8" multiTemplateDataRows>
<!--    <table mat-table [dataSource]="pokemon.results" class="mat-elevation-z8" multiTemplateDataRows>-->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
<!--  <td mat-cell *matCellDef="let res"> {{res?.name}} </td>-->
      <td mat-cell *matCellDef="let res"> {{res.name}} </td>
    </ng-container>
    <ng-container matColumnDef="url">
      <th mat-header-cell *matHeaderCellDef> URL </th>
      <td mat-cell *matCellDef="let res"> {{res.url}} </td>
    </ng-container>
    <ng-container matColumnDef="pokemonDetails">
      <th mat-header-cell *matHeaderCellDef> Pokemon Details </th>
      <td mat-cell *matCellDef="let res">
        <button mat-raised-button color="primary" routerLink="/pokemonData/{{res.name}}">Pokemon Details</button>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="displayPokemonColumns; sticky: true"></tr>
    <tr mat-row *matRowDef="let row; columns: displayPokemonColumns;"
        class="example-element-row"
        [class.example-expanded-row]="expandedElement === row"
        (click)="expandedElement = expandedElement === row ? null : row"></tr>
    </table>
  <mat-paginator #paginator
                 [pageSize]="10"
                 [pageSizeOptions]="[5, 10, 20]">
  </mat-paginator>
</div>

this is the data I get back:

MatTableDataSource {_renderData: BehaviorSubject, _filter: BehaviorSubject, _internalPageChanges: Subject, _renderChangesSubscription: Subscriber, sortingDataAccessor: ƒ, …}filterPredicate: (data, filter) => {…}filteredData: {count: 1050, next: "https://pokeapi.co/api/v2/pokemon?offset=150&limit=150", previous: null, results: Array(150)}sortData: (data, sort) => {…}sortingDataAccessor: (data, sortHeaderId) => {…}_data: BehaviorSubject {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}_filter: BehaviorSubject {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}_internalPageChanges: Subject {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false, …}_paginator: undefined_renderChangesSubscription: Subscriber {closed: false, _parentOrParents: null, _subscriptions: Array(1), syncErrorValue: null, syncErrorThrown: false, …}_renderData: BehaviorSubject {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}data: (...)filter: (...)paginator: (...)sort: (...)__proto__: DataSource

The data I need is under filteredData.

When I do

<table mat-table [dataSource]="pokemon.results" class="mat-elevation-z8" multiTemplateDataRows>

instead of dataSource, I get the correct table, but the paginator (obviously) doesn't work.

解决方案

what worked in the end, was removing the *ngIf condition on the template. I found this solution on stack overflow. Paginator now works fine.

这篇关于Mat Table 的 Mat Paginator 无法处理 api 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆