角材料表

时间:2020-10-11 13:39:56

标签: angular angular-material frontend material-design web-frontend

我正在学习Angular,并且正在使用调用API来接收数据以填充表。

该表的记录未显示。但是使用console.log,我可以在控制台中看到它们。

这是我的组件。

export class ListaUtentiComponent implements OnInit {

  displayedColumns =  ['id', 'username'];
  @Input()
  dataSource: MatTableDataSource<any>;

  utenti: Utenti [];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(public rest: ApiService, private router: Router) { }

  ngOnInit(): void {
    this.dataSource = new MatTableDataSource();
    this.getUser();
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

 getUser() {
    this.rest.getUsers().subscribe((data) => {
      console.log(data);
      alert(data);
      this.dataSource['data']; 
      return data;


    });
  }
}

这是我的component.html

<div class="mat-elevation-z8">
  <table mat-table class="full-width-table" matSort aria-label="Elements" [dataSource]="dataSource">
    
<ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
      <td mat-cell *matCellDef="let ut">{{ut.id}}</td>
    </ng-container>

 
   <ng-container matColumnDef="username">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Nome</th>
      <td mat-cell *matCellDef="let ut">{{ut.name}}</td>
    </ng-container> 

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

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

请帮助我,我不知道怎么了。

2 个答案:

答案 0 :(得分:1)

我看不到任何将获取的数据分配给mat-table的dataSource的代码。

您需要做的就是更新数据源,例如:

getUser() {
    this.rest.getUsers().subscribe((data) => {
      this.dataSource = data;
    });
}

答案 1 :(得分:0)

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface ListaUtentiItem {
        id: string,
        email: string,
        emailConfirmed: boolean,
        passwordHash: string,
        securityStamp: string,
        phoneNumber: string,
        phoneNumberConfirmed: boolean,
        twoFactorEnabled: boolean,
        lockoutEndDateUtc: string,
        lockoutEnabled: boolean,
        accessFailedCount: number,
        userName:string
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: ListaUtentiItem[] = [
  // {id: 1, name: 'Hydrogen'},
  // {id: 2, name: 'Helium'},
  // {id: 3, name: 'Lithium'},
  // {id: 4, name: 'Beryllium'},
  // {id: 5, name: 'Boron'},
  // {id: 6, name: 'Carbon'},
  // {id: 7, name: 'Nitrogen'},
  // {id: 8, name: 'Oxygen'},
  // {id: 9, name: 'Fluorine'},
  // {id: 10, name: 'Neon'},
  // {id: 11, name: 'Sodium'},
  // {id: 12, name: 'Magnesium'},
  // {id: 13, name: 'Aluminum'},
  // {id: 14, name: 'Silicon'},
  // {id: 15, name: 'Phosphorus'},
  // {id: 16, name: 'Sulfur'},
  // {id: 17, name: 'Chlorine'},
  // {id: 18, name: 'Argon'},
  // {id: 19, name: 'Potassium'},
  // {id: '20', userName: 'Calcium',},
];

/**
 * Data source for the ListaUtenti view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class ListaUtentiDataSource extends DataSource<ListaUtentiItem> {
  data: ListaUtentiItem[] = EXAMPLE_DATA;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
   super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<ListaUtentiItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: ListaUtentiItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: ListaUtentiItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'username': return compare(a.userName, b.userName, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

这是