Angular Material - mat-table 不渲染来自 rest api 的数据 [英] Angular Material - mat-table not rendering data from rest api

查看:22
本文介绍了Angular Material - mat-table 不渲染来自 rest api 的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试实现 this 来自 Angular Material 的表格示例,但不幸的是

我不明白我做错了什么,我的 REST 端点提供的数据在控制台输出中清晰可见.

我怀疑可能是在呈现表格时数据还没有完全加载.感谢任何帮助,谢谢!

lap.component.ts

import {Component, OnInit, ViewChild} from '@angular/core';从@angular/material"导入 {MatPaginator、MatSort、MatTableDataSource};从 '@angular/router' 导入 {Router};从'../shared/services/lap.service'导入{LapService};从'../shared/model/lap.model'导入{Lap};@成分({选择器:'app-lap',templateUrl: './lap.component.html',styleUrls: ['./lap.component.css']})导出类 LapComponent 实现 OnInit {displayColumns = ['id', 'year', 'lap', 'shortcut flag', 'start place', 'destination place', 'length', '高度差'];数据源:MatTableDataSource;@ViewChild(MatPaginator) 分页器:MatPaginator;@ViewChild(MatSort) 排序:MatSort;构造函数(公共休息:LapService,私有路由器:路由器){}ngOnInit() {this.dataSource = new MatTableDataSource(this.getLaps());this.dataSource.paginator = this.paginator;this.dataSource.sort = this.sort;}应用过滤器(过滤器值:字符串){this.dataSource.filter = filterValue.trim().toLowerCase();如果(this.dataSource.paginator){this.dataSource.paginator.firstPage();}}获取圈数(){this.rest.getLaps().subscribe((data: {}) => {控制台日志(数据);console.log('圈数');返回数据;});}}

lap.component.html

<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter"></mat-form-field><div class="mat-elevation-z8"><table mat-table [dataSource]="dataSource" matSort><!-- ID 列--><ng-container matColumnDef="id"><th mat-h​​eader-cell *matHeaderCellDef mat-sort-header>ID </th><td mat-cell *matCellDef="let row ">{{row.id}} </td></ng-容器><!-- 年份栏--><ng-container matColumnDef="year"><th mat-h​​eader-cell *matHeaderCellDef mat-sort-header>年</th><td mat-cell *matCellDef="let row">{{row.year}} </td></ng-容器><!-- 圈数列--><ng-container matColumnDef="lap"><th mat-h​​eader-cell *matHeaderCellDef mat-sort-header>圈</th><td mat-cell *matCellDef="let row">{{row.lap}} </td></ng-容器><!-- 快捷栏--><ng-container matColumnDef="快捷方式标志"><th mat-h​​eader-cell *matHeaderCellDef mat-sort-header>快捷方式标志</th><td mat-cell *matCellDef="let row" [style.color]="row.color">{{row.shortcut_flag}} </td></ng-容器><!-- 起始列--><ng-container matColumnDef="起始位置"><th mat-h​​eader-cell *matHeaderCellDef mat-sort-header>起始地点</th><td mat-cell *matCellDef="let row">{{row.start_place}} </td></ng-容器><!-- 目标列--><ng-container matColumnDef="目的地"><th mat-h​​eader-cell *matHeaderCellDef mat-sort-header>目的地</th><td mat-cell *matCellDef="let row">{{row.destination_place}} </td></ng-容器><!-- 长度列--><ng-container matColumnDef="length"><th mat-h​​eader-cell *matHeaderCellDef mat-sort-header>长度</th><td mat-cell *matCellDef="let row">{{row.length}} </td></ng-容器><!-- 高度列--><ng-container matColumnDef="高度差"><th mat-h​​eader-cell *matHeaderCellDef mat-sort-header>高度差</th><td mat-cell *matCellDef="let row">{{row.height_difference}} </td></ng-容器><tr mat-h​​eader-row *matHeaderRowDef="displayedColumns"></tr><tr mat-row *matRowDef="让行;列:displayColumns;"></tr><mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>

lap.service.ts

从'@angular/core'导入{Injectable};从@angular/common/http"导入 {HttpClient, HttpHeaders};从 'rxjs' 导入 {Observable};从 'rxjs/operators' 导入 {map};@Injectable({提供在:'根'})导出类 LapService {private lapUrl = 'http://localhost:8080/api/lap';私有 httpOptions = {标头:新的 HttpHeaders({'内容类型':'应用程序/json'})};构造函数(私有http:HttpClient){}getLaps(): Observable{返回 this.http.get(this.lapUrl, this.httpOptions).pipe(地图(this.extractData));}私人提取数据(资源:响应){返回资源 ||{};//如果'res'为空,则返回空对象}}

解决方案

您需要创建 new MatTableDataSource() 然后在接收数据时将该数据传递给 dataSource.data 数组.

 ngOnInit() {//this.dataSource = new MatTableDataSource(this.getLaps());this.dataSource = new MatTableDataSource();//创建新对象this.getLaps();//忘记了这一行this.dataSource.paginator = this.paginator;this.dataSource.sort = this.sort;}获取圈数(){this.rest.getLaps().subscribe((data: {}) => {控制台日志(数据);console.log('圈数');this.dataSource.data = 数据;//在数据接收时填充 dataSource.data 数组返回数据;});}

I've been trying to implement this table example from Angular Material without luck

I don't understand what I'm doing wrong, the data which is being provided by my REST endpoint is clearly visible on the console output.

My suspicions are that maybe the data isn't quite loaded yet, when the table is rendered. Any help is appreciated, thanks!

lap.component.ts

import {Component, OnInit, ViewChild} from '@angular/core';
import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';
import {Router} from '@angular/router';
import {LapService} from '../shared/services/lap.service';
import {Lap} from '../shared/model/lap.model';

@Component({
  selector: 'app-lap',
  templateUrl: './lap.component.html',
  styleUrls: ['./lap.component.css']
})
export class LapComponent implements OnInit {

  displayedColumns = ['id', 'year', 'lap', 'shortcut flag', 'start place', 'destination place', 'length', 'height difference'];
  dataSource: MatTableDataSource<Lap>;

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


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

  ngOnInit() {
    this.dataSource = new MatTableDataSource(this.getLaps());
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }


  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  getLaps() {
    this.rest.getLaps().subscribe((data: {}) => {
      console.log(data);
      console.log('Laps');
      return data;
    });
  }
}

lap.component.html

<mat-form-field>
  <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>

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

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

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

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

    <!-- Shortcut Column -->
    <ng-container matColumnDef="shortcut flag">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Shortcut Flag </th>
      <td mat-cell *matCellDef="let row" [style.color]="row.color"> {{row.shortcut_flag}} </td>
    </ng-container>

    <!-- Start Column -->
    <ng-container matColumnDef="start place">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Start Place </th>
      <td mat-cell *matCellDef="let row"> {{row.start_place}} </td>
    </ng-container>

    <!-- Destination Column -->
    <ng-container matColumnDef="destination place">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Destination Place </th>
      <td mat-cell *matCellDef="let row"> {{row.destination_place}} </td>
    </ng-container>

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

    <!-- Height Column -->
    <ng-container matColumnDef="height difference">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Height Difference </th>
      <td mat-cell *matCellDef="let row"> {{row.height_difference}} </td>
    </ng-container>

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

  <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>

lap.service.ts

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class LapService {

  private lapUrl = 'http://localhost:8080/api/lap';
  private httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

  constructor(private http: HttpClient) { }

  getLaps(): Observable<any> {
    return this.http.get(this.lapUrl, this.httpOptions).pipe(
      map(this.extractData));
  }

  private extractData(res: Response) {
    return res || {}; // If 'res' is null, it returns empty object
  }

}

解决方案

You need to create new MatTableDataSource() and then on data receiving pass that data to dataSource.data array.

 ngOnInit() {
   // this.dataSource = new MatTableDataSource(this.getLaps());
    this.dataSource = new MatTableDataSource(); // create new object
    this.getLaps(); // forgeted this line
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
 }

   getLaps() {
     this.rest.getLaps().subscribe((data: {}) => {
       console.log(data);
       console.log('Laps');
       this.dataSource.data = data; // on data receive populate dataSource.data array
       return data;
    });
  }

这篇关于Angular Material - mat-table 不渲染来自 rest api 的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆