首页 > 解决方案 > 角度垫表:无法读取未定义的属性“地图”

问题描述

在尝试以角度创建垫表时,我收到Cannot read property 'map' of undefined使用以下代码的错误。谁能看到我哪里出错了:我的 API 正在工作,但由于某种原因,我似乎无法将它绑定到数据源。

user.service.ts:

getUsers() {
  this.http
    .get<{ message: string; users: any }>("http://3.130..???/api/users")
    .pipe(
      map(employeeData => {
        return employeeData.users.map(user => {
          return {
            id: user._id,
            email: user.email,
            password: user.password,
            userType: user.userType,
          };
        });
      })
    )
    .subscribe(transformedUsers => {
      this.users = transformedUsers;
      this.usersUpdated.next([...this.users]);
    });
}

getUserUpdateListener() {
  return this.usersUpdated.asObservable();
}

userList.component.ts:

export class UserListComponent {
  Page = "User Table"
  @ViewChild(MatSort) sort: MatSort;
  users: User[] = [];
  private usersSub: Subscription;
  displayedColumns: string[] = ["id", "email", "password"];
  dataSource: MatTableDataSource<User>;

  constructor(
    private usersService: UsersService,
    public dialog: MatDialog
  ) {
    this.usersService.getUsers();
    this.usersSub = this.usersService.getUserUpdateListener()
      .subscribe((users: User[]) => {
        this.users = users;
        this.dataSource = new MatTableDataSource<User>(this.users);
        this.dataSource.sort = this.sort;
        console.log(this.dataSource)
        console.log(this.users)
      });
  }

userList.component.html:

<div class="container">
  <table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z3">

    <!-- id Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> id </th>
      <td mat-cell *matCellDef="let employee"> {{employee.id}} </td>
    </ng-container>

    <!-- email Column -->
    <ng-container matColumnDef="email">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> email </th>
      <td mat-cell *matCellDef="let employee"> {{employee.email}} </td>
    </ng-container>

    <!-- password Column -->
    <ng-container matColumnDef="password">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> password </th>
      <td mat-cell *matCellDef="let employee"> {{employee.password}} </td>
    </ng-container>

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

标签: angulartypescriptangular-material

解决方案


推荐阅读