【问题标题】:mat-table angular 6 not showing any data despite having the dataSource尽管有 dataSource,mat-table angular 6 没有显示任何数据
【发布时间】:2018-11-13 09:02:17
【问题描述】:

我想通过 Angular Material Design 的数据表 mat-table 显示一个列表。 这是我的组件:

import { LeaveapplicationService } from './../../services/leaveapplication.service';
import { leaveapplication } from './../../models/leaveapplication';
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
// import { DataSource } from '@angular/cdk/table';

@Component({
  selector: 'app-leaveapplication-list',
  templateUrl: './leaveapplication-list.component.html',
  styleUrls: ['./leaveapplication-list.component.scss']
})
export class LeaveapplicationListComponent implements OnInit {
  leaveApplications: leaveapplication[];
  displayedColumns: ['id', 'applicant', 'manager', 'leavetype', 'start', 'end', 'return', 'status'];
  dataSource: MatTableDataSource<leaveapplication>;

  constructor(private leaveApplicationService: LeaveapplicationService) { }

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.leaveApplicationService.getLeaveApplications().subscribe(leaveapplications => {
      this.leaveApplications = leaveapplications;
      this.dataSource = new MatTableDataSource<leaveapplication>(this.leaveApplications);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
      console.log(this.dataSource);
    });

  }

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }
}

请假申请界面:

export interface leaveapplication {
  id: number; 
  applicant: string;
  manager: string;
  startdate: Date;
  enddate: Date;
  returndate: Date;
  leavetype: string; 
  status: string;
}

我在控制台中正确获取数据源:

但是垫表返回空单元格:

这是我的模板:

<mat-form-field>
  <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
<mat-table #table [dataSource]="dataSource" matSort class="mat-elevation-z8">
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Form ID </th>
    <td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.id}} </td>
  </ng-container>
  <ng-container matColumnDef="applicant">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Applicant </th>
    <td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.applicant}} </td>
  </ng-container>

  <ng-container matColumnDef="manager">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Manager </th>
    <td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.manager}} </td>
  </ng-container>

  <ng-container matColumnDef="leavetype">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Leave Type </th>
    <td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.leaveType}} </td>
  </ng-container>
  <ng-container matColumnDef="start">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Start Date </th>
    <td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.startDate | date:'dd-MM-yyyy'}} </td>
  </ng-container>
  <ng-container matColumnDef="end">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> End Date </th>
    <td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.endDate | date:'dd-MM-yyyy'}} </td>
  </ng-container>
  <ng-container matColumnDef="return">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Return Date </th>
    <td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.returnDate | date:'dd-MM-yyyy'}} </td>
  </ng-container>
  <ng-container matColumnDef="status">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Status </th>
    <td mat-cell *matCellDef="let leaveapplication"> {{leaveapplication.status}} </td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</mat-table>

<mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>

为什么我没有填充 mat-table?是因为响应的异步特性吗?

【问题讨论】:

    标签: angular typescript datatable material-design


    【解决方案1】:

    尝试检查是否设置了this.leaveApplications。

    ngOnInit() {
    this.leaveApplicationService.getLeaveApplications().subscribe(leaveapplications => {
      this.leaveApplications = leaveapplications;
      if (this.leaveApplications) {
         this.dataSource = new MatTableDataSource<leaveapplication>(this.leaveApplications);
          this.dataSource.paginator = this.paginator;
          this.dataSource.sort = this.sort;
          console.log(this.dataSource);
      }
     });
    }
    

    【讨论】:

      【解决方案2】:

      您好,我有一个类似的问题,我可以记录数据源的数据,但数据表不显示数据。

      我在我的服务中创建了一个模拟数据数组并传递了它,而不是我从数据库中获得的结果。使用 Mock-Array 它可以工作,并且我的 mat-table 中填充了数据。

      在我记录了数据库和模拟数据的结果之后,在控制台中我注意到我从数据库中获取了一个带有数组的对象,而不仅仅是一个数组。

      浏览器控制台 ->

      模拟数据:[ {...} ]

      数据库:{ [ {...} ] }

      如果您仔细观察,您可以在浏览器 DOM 中看到,数据源设置为 [Object object],我认为存在问题,因为 Mat-Table 无法访问数据。

      我找到了一个解决方法,我传递对象的数组而不是对象,这有点脏,但是直到我找到问题的根源为止。

      这是我的服务:

      rfc.service.ts

      @Injectable({
        providedIn: 'root'
      })
      export class RfcService {
        rfcsChanged = new Subject<Rfc[]>();
        private dbSubs: Subscription[] = [];
      
        <<MOCK-DATA>>
      
        constructor(private http: HttpClient) { }
      
        httpOptions = {
          headers: new HttpHeaders({
            'Content-Type': 'application/json'
          })
        };
      
        fetchRfcs() {...}
      
        cancelSubscriptions() {
          this.dbSubs.forEach(sub => sub.unsubscribe());
        }
      

      在我更改代码后:

      fetchRfcs() {
        this.dbSubs.push(
          this.http.get<Rfc[]>('http://localhost:3000/rfcs')
           .subscribe((rfcs: Rfc[]) => {
             // console.log(this.MOCK_RFCS);
             // console.log(rfcs);
             this.rfcsChanged.next(rfcs); 
           })
        );
      }
      

      到:

      fetchRfcs() {
        this.dbSubs.push(
          this.http.get<Rfc[]>('http://localhost:3000/rfcs')
           .subscribe((rfcs: Rfc[]) => {
              // console.log(this.MOCK_RFCS);
              // console.log(rfcs.rfcs);
              this.rfcsChanged.next(rfcs.rfcs); 
           })
          );
      }
      

      成功了。

      我不知道为什么我的响应数组被包装在一个对象中,但我建议检查您的服务以及它如何接收数据。目前我试图找到一种方法来映射我从后端的响应,这样它就不会被包裹在一个对象中。

      如何在服务中检索数据?

      【讨论】:

      • 基本上就是这样。我仔细查看了我借用的服务实现,发现它正在将结果通过管道传输到地图,这对于我的后端提供的数据来说是不需要的。很好的故障排除,Jan!
      【解决方案3】:

      在上述HTML代码的ng-container中修改如下。

      From matColumnDef="start" to matColumnDef="startDate" From matColumnDef="end" to matColumnDef="endDate " From matColumnDef="return" to matColumnDef="returnDate"

      matColumnDef 必须与数据列完全匹配,否则数据不会显示在 mat-table 中。

      【讨论】:

        【解决方案4】:

        您的 component.ts 文件中有一个错字:您没有将显示的列数组分配给 displayedColumns,而只是定义了您的变量。

        所以,而不是

         displayedColumns: ['id', 'applicant', 'manager', 'leavetype', 'start', 'end', 'return', 'status'];
        

        应该是

         displayedColumns: string[] = ['id', 'applicant', 'manager', 'leavetype', 'start', 'end', 'return', 'status'];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-06-13
          • 2019-09-18
          • 2019-06-03
          • 2020-08-04
          • 2018-12-24
          • 1970-01-01
          • 1970-01-01
          • 2020-01-28
          相关资源
          最近更新 更多