首页 > 解决方案 > Angular Material 数据表 - 尝试加载数据

问题描述

我正在使用下面的 TS 代码通过 Bootstrap 表加载数据,并且我想在小幅提升后试验 Angular Material Data 表。此时我只能加载表头,但找不到如何显示数据。没有抛出错误,我插入的控制台日志说:

Observable -> MapOperator -> thisArg: 未定义

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { AngularFirestore } from '@angular/fire/firestore';

@Component({
  selector: 'app-tasks',
  templateUrl: './tasks.component.html',
  styleUrls: ['./tasks.component.scss']
})
export class TasksComponent implements OnInit {
  tasks: Observable<any[]>;

  displayedColumns = ['description', 'note'];
  dataSource: MatTableDataSource<Tasks>;

  constructor(private db: AngularFirestore) {}

  ngOnInit() {
    this.tasks = this.db
      .collection('tasks')
      .snapshotChanges()
      .pipe(
        map(actions => {
          return actions.map(a => {
            const data = a.payload.doc.data() as Tasks;
            const id = a.payload.doc.id;
            return { id, ...data };
          });
        })
      );

  console.log(this.tasks);
  return this.tasks;
  }
}

export interface Tasks {
  description: string;
  note: string;
}

这是我的 HTML:

<mat-table #table [dataSource]="dataSource">
  <ng-container matColumnDef="description">
    <mat-header-cell *matHeaderCellDef> description </mat-header-cell>
    <mat-cell *matCellDef="let task">{{task.description}}</mat-cell>
  </ng-container>

  <ng-container matColumnDef="note">
    <mat-header-cell *matHeaderCellDef> note </mat-header-cell>
    <mat-cell *matCellDef="let task">{{task.note}}</mat-cell>
  </ng-container>

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

我正在使用带有当前软件包版本的 Angular 7,并且数据库包含记录,那么我在这里做错了什么?

标签: angulartypescriptfirebaseangular-material

解决方案


你应该试试这个代码......

    <mat-table class="highlight" #table [dataSource]="dataSource" matSort>
 <!-- Dynamic      -->
        <ng-container *ngFor="let col of displayedColumns" matColumnDef={{col}}>
          <mat-header-cell *matHeaderCellDef mat-sort-header>{{col.replace('_', ' ')| titlecase }} </mat-header-cell>
          <mat-cell *matCellDef="let Exception">
            <span>{{Exception[col]}}</span>
          </mat-cell>
        </ng-container>
 <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
      </mat-table>

TS

        import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';

/* 数据源:MatTableDataSource; 将其替换为 */

dataSource = new MatTableDataSource();
             this.dataSource.data = this.Task;

推荐阅读