【问题标题】:How to display data from API in Angular Material table?如何在 Angular Material 表中显示来自 API 的数据?
【发布时间】:2019-06-23 15:50:11
【问题描述】:

我有一个包含数据的 API(数组中的数组等)。我想在数据表中显示其中的一些数据。 代码如下:

首先我有customer.ts 模型

export interface CustomerResponce {
  working_periods: Customer[];
}
export interface Customer {
  id: number;
  personal_number?: number;
  contact_number?: number;
  start_date?: Date;
  end_date?: Date;
  submitted_at?: Date;
  approved_by_contact_number?: string;
  approved_by_personal_number?: number;
  approved_at?: Date;
  external_employee_notes?: string;
  internal_employee_notes?: string;
  customer_notes?: string;
  external_employee_signature?: string;
  customer_signature?: string;
  job_number?: number;
  consecutive_service_number?: number;
  location_number?: number;
  consecutive_operation_number?: number;
  status?: number;
  original_time_frames?: WorkingPeriod[];
}
export interface WorkingPeriod {
  working_period_id?: number;
  started_at?: Date;
  ended_at?: Date;
  pauses?: Pauses[];
  activity?: string;
}
export interface Pauses {
  start?: Date;
  end?: Date;
}

然后我有activityReport.ts 服务

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
import { Customer, CustomerResponce} from '../_models/customer';
import { catchError } from 'rxjs/operators';
import {BehaviorSubject} from 'rxjs';
import { id } from '@swimlane/ngx-datatable/release/utils';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class ActivityReportsService {
  private filterStatus;
  private _customer: BehaviorSubject<Customer[]>;
  private  TN_API = 'https://localhost:3000/api/v2/working_periods';

  constructor(
    private http: HttpClient,
    private router: Router
    ) {
  }

  getAll() {
    const httpOptions = {
      headers: new HttpHeaders({
        Authorization: `Token token=${localStorage.getItem('access_token')}`
      })
    };
    return this.http.get<CustomerResponce>(this.TN_API, httpOptions);
  }

  setFilterStatus(status: string|null = null): void {
    if (this.router.url !== '/dashboard/list') {
      this.router.navigate(['/dashboard/list']);
    }
    this.filterStatus = status;
  }

  getFilterStatus(): string|null {
    return this.filterStatus;
  }

  updateWorkingPeriod (periodId: number, workingPeriod) {
    const httpOptions = {
      headers: new HttpHeaders({
        Authorization: `Token token=${localStorage.getItem('access_token')}`
      })
    };
    return this.http.put(this.TN_API + '/' + periodId, workingPeriod, httpOptions);
  }

}

我还有dashboard.component.html 有我的桌子:

<div class="row">
  <div class="col-lg-12">
    <div class="card">
      <div class="card-body">
        <h2>Table 2</h2>
        <mat-form-field>
            <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Search">
        </mat-form-field>

        <div class="mat-elevation-z8">
          <table mat-table [dataSource]="dataSource" matSort>
            <ng-container matColumnDef="start_date">
              <th mat-header-cell *matHeaderCellDef mat-sort-header>Mitarbeiter</th>
              <td mat-cell *matCellDef="let customers">{{ customers.start_date}} </td>
            </ng-container>

            <ng-container matColumnDef="end_date">
              <th mat-header-cell *matHeaderCellDef mat-sort-header>Einsatz</th>
              <td mat-cell *matCellDef="let customers">{{customers.end_date}} </td>
            </ng-container>

            <ng-container matColumnDef="approved_at">
              <th mat-header-cell *matHeaderCellDef mat-sort-header>Eingangsdatum</th>
              <td mat-cell *matCellDef="let customers">{{customers.approved_at}}</td>
            </ng-container>

            <ng-container matColumnDef="submitted_at">
              <th mat-header-cell *matHeaderCellDef mat-sort-header>Zeitraum</th>
              <td mat-cell *matCellDef="let customers">{{customers.submitted_at}}</td>
            </ng-container>

            <ng-container matColumnDef="status">
              <th mat-header-cell *matHeaderCellDef mat-sort-header>Status</th>
              <td mat-cell *matCellDef="let customers">{{customers.status}}</td>
            </ng-container>
            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

终于有dashboard.component.ts:

import {Component, OnInit, OnDestroy, ViewChild, AfterViewInit} from '@angular/core';
import { Subscription} from 'rxjs';
import { ActivityReportsService } from '../../services/activity-reports.service';
import { CustomerLoginService } from '../../services/customer-login.service';
import { Customer, CustomerResponce } from '../../_models/customer';
import {MatTableDataSource, MatSort, MatPaginator} from '@angular/material';

@Component({
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})

export class DashboardComponent implements OnInit, OnDestroy {
  currentUser: Customer;
  currentUserSubscription: Subscription;
  customers: Customer[] = [];
  dataSource: MatTableDataSource<Customer>;
  displayedColumns: string[] = ['start_date', 'end_date', 'approved_at', 'submitted_at', 'status'];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(
    private customerLoginService: CustomerLoginService,
    public activityReportService: ActivityReportsService
  ) {
    this.currentUserSubscription = this.customerLoginService.currentUser.subscribe(customer => {
      this.currentUser = customer;
      this.dataSource = new MatTableDataSource(this.customers);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
      console.log(this.dataSource);
    });
  }

  ngOnInit() {
    this.loadAllReports();
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    console.log(this.dataSource);
  }

  ngOnDestroy() {
    this.currentUserSubscription.unsubscribe();
  }

  private loadAllReports() {
    this.activityReportService.getAll().subscribe((customers: CustomerResponce) => {
      this.customers = customers.working_periods;
      localStorage.setItem('activityTN', JSON.stringify(customers));
    });
  }

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }
}

我上面显示的代码给了我这个结果:

请帮助我显示数据。 TIA

【问题讨论】:

    标签: angular datatable angular-material


    【解决方案1】:

    您能否尝试将customers 名称更改为item 或其他名称。

    此时:

    <ng-container matColumnDef="start_date">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Mitarbeiter</th>
      <td mat-cell *matCellDef="let customers">{{ customers.start_date}} </td>
    </ng-container>
    

    我认为应该是:

    <td mat-cell *matCellDef="let item">{{ item.start_date}} </td>
    

    而不是:

    <td mat-cell *matCellDef="let customers">{{ customers.start_date}} </td>
    

    您应该更改所有 mat-cell 行。

    【讨论】:

    • 我改了也没用。也可以帮我检查一下component.ts吗?
    • 在浏览器控制台上可以写错误吗?
    • 浏览器没有出现错误。该表不显示任何内容。
    【解决方案2】:

    您的模板缺少mat-row 定义。它需要插入到mat-header-row 下方。这可能如下所示(未经测试)。

    <tr mat-header-row *matHeaderRowDef="frameColumns; sticky: true"></tr> // existing
    <tr mat-row *matRowDef="let customer; columns: displayedColumns"></tr>
    

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 2020-03-12
      相关资源
      最近更新 更多