我正在try 通过API的动态数据填充MAT-TABLE. 正在填充数据,但分页部分没有响应. 我在Stackoverflow上try 了以下链接中提供的解决方案,但都没有奏效.我使用的是Angular 16和Angular material 16.2.10

Solution1

Solution2

Solution3

Solution4

Solution5

Pfb我的代码: Component.ts:

import { HttpClient } from '@angular/common/http';
import { Component, OnInit, ViewChild, AfterViewInit, ChangeDetectorRef } from '@angular/core';
import {MatPaginator, MatPaginatorModule} from '@angular/material/paginator';
import {MatTableDataSource, MatTableModule} from '@angular/material/table';

@Component({
  selector: 'app-test-api',
  templateUrl: './test-api.component.html',
  styleUrls: ['./test-api.component.css'],
  standalone: true,
  imports: [MatTableModule, MatPaginatorModule]
})
export class TestAPIComponent implements OnInit, AfterViewInit {
  public displayedColumns: string[] = ['id', 'name', 'email', 'city', 'latitude'];
  public getJsonValue: any;
  public dataSource: any = [];
//code for pagination: tried all solutions from stackoverflow , none worked
@ViewChild(MatPaginator) paginator: MatPaginator;
  //@ViewChild(MatPaginator, {read: true}) paginator: MatPaginator;
  
  /*@ViewChild(MatPaginator, {static: false})
  set paginator(value: MatPaginator) {
    this.dataSource.paginator = value;
  } */

  /*@ViewChild(MatPaginator) set matPaginator(mp: MatPaginator) {
    this.paginator = mp;
    this.dataSource.paginator = this.paginator;
}*/
  
  constructor(private http : HttpClient){

  }
  ngOnInit(): void {
    this.getMethod();
    //this.cdr.detectChanges();
  }

  public getMethod(){
    this.http.get('https://jsonplaceholder.typicode.com/users').subscribe((data) => {
      console.table(data);
      console.log(this.paginator);
      this.getJsonValue = data;
      this.dataSource = data;
      //tried below code from stackoverflow but didn't work and commented ngAfterViewInit code
      this.dataSource.paginator = this.paginator;
    });
    
  }

  ngAfterViewInit() {
   //this.dataSource.paginator = this.paginator;
  }  
}

HTML:

<p>test-api works!</p>
<H1>Test API</H1>
<!--p>{{getJsonValue | json}}</p-->

<h1>Test API: Dynamic</h1>
<p>dynamic-table works!</p>

<div class="mat-elevation-z8">
    <table mat-table [dataSource]="dataSource">
  
      <!-- Position Column -->
      <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef> Id </th>
        <td mat-cell *matCellDef="let element"> {{element.id}} </td>
      </ng-container>
  
      <!-- Name Column -->
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
      </ng-container>
  
      <!-- Weight Column -->
      <ng-container matColumnDef="email">
        <th mat-header-cell *matHeaderCellDef> email </th>
        <td mat-cell *matCellDef="let element"> {{element.email}} </td>
      </ng-container>
  
      <!-- Symbol Column -->
      <ng-container matColumnDef="city">
        <th mat-header-cell *matHeaderCellDef> city </th>
        <td mat-cell *matCellDef="let element"> {{element.address.city}} </td>
      </ng-container>

      <!-- Symbol Column -->
      <ng-container matColumnDef="latitude">
        <th mat-header-cell *matHeaderCellDef> Latitude </th>
        <td mat-cell *matCellDef="let element"> {{element.address.geo.lat}} </td>
      </ng-container>
  
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>
  
    <mat-paginator [pageSizeOptions]="[5, 10, 20]"
    [pageSize]="5"
                   showFirstLastButtons
                   aria-label="Select page of periodic elements">
    </mat-paginator>
  </div>
  

Current Table UI with disabled pagination: enter image description here

推荐答案

将变量定义为MatTableDataSource

dataSource!:MatTableDataSource<any>

当你得到它的时候

public getMethod(){
    this.http.get('https://jsonplaceholder.typicode.com/users').subscribe((data:any[]) => {
      //you create a MatTableDataSource
      this.dataSource = new MatTableDataSource(data);
      //you asig the paginator
      this.dataSource.paginator = this.paginator;
    });
    
  }

注意:您应该使用服务来获取数据(这被认为是"良好的做法",而不是在您的组件中使用http客户端,例如

@Injectable({
  providedIn: 'root',
})
export class DataService {
  constructor(private httpClient:HttpClient) { }

  //simply return an observable
  getData():Observable<any[]> { //<--indicate the return of the function
    return this.httpClient.get<any[]>('https://jsonplaceholder.typicode.com/users') //<--indicate in get the type
  }
}

在您的组件中

  constructor(private dataService:DataService){}

  //and use

    public getMethod(){
        this.dataService.getData().subscribe((data:any[]) => {
          this.dataSource = new MatTableDataSource(data);
          this.dataSource.paginator = this.paginator;
        });
        
      }

Angular相关问答推荐

iOS Mobile Safari - HTML5视频覆盖一切

身份验证卫士给了我17个Angular 的任何类型

更改图表上的光标以进行zoom

倒计时计时器,每10秒重新启动一次,共4次

如何在 Angular RxJS 中替换订阅中的 subscrib?

npm install命令在基本Angular 应用程序的天蓝色构建管道中失败

Angular 15 Ref 错误:初始化前无法访问组件 A

如何在 Angular14 中创建带有验证的自定义输入组件?

MatTooltip 显示在 html 原生对话框下方

如何使用指令以Angular 传递默认值

将 html ngModel 值传递给服务Angular

Angular 2 中的 ChangeDetectionStrategy.OnPush 和 Observable.subscribe

全局异常处理

RxJS - .withLatestFrom 的多个来源

怎样在 Angular 2 或 4 中将输入字段设为只读?

ng test 和 ng e2e 之间的真正区别是什么

未绑定断点 - VS Code | Chrome | Angular

unexpected token < 错误

从 angular2 模板调用静态函数

来自 chokidar (C:\) 的错误:错误:EBUSY:资源繁忙或锁定,lstat 'C:\DumpStack.log.tmp