从服务绑定dataTable的问题

时间:2019-05-01 12:45:21

标签: angular angular-material

我有一个获取数据的服务,但是当我尝试通过getPost()方法填充数据表时。

我有一个获取数据的服务,但是当我尝试从getPost()方法填充数据表时,它给了我这个错误。 找不到ID为“ body”的列。     在getTableUnknownColumnError

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { IPost } from './Ipost';

@Injectable({
  providedIn: 'root'
})
export class PostService {
  url ="https://jsonplaceholder.typicode.com/posts";
  constructor(private http: HttpClient) { }
  

  public getPosts(): Observable<IPost[]> {
    return this.http.get<IPost[]>(this.url);
  }

  public getPosts2()  {
    return this.http.get(this.url);
  }
}


export interface IPost{
    id: any;
    title: any;
    body: any
  }

组件中的

代码

import { Component, OnInit } from '@angular/core';
import { PostService } from '../services/post-services.service';
import { IPost } from '../services/Ipost';
@Component({
  selector: 'app-datatable',
  templateUrl: './datatable.component.html',
  styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {

  constructor(private service: PostService) { }
  displayedColumns: string[] = ['id', 'title', 'body'];
  // dataSource :IPost[] = [];
  dataSource;
  ngOnInit() {
    this.service.getPosts().subscribe(data => {
      console.log(data);
      this.dataSource = data['data'];

    }
    )
  }

}

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

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

  <!-- Title Column -->
  <ng-container matColumnDef="title">
    <th mat-header-cell *matHeaderCellDef> Title </th>
    <td mat-cell *matCellDef="let element"> {{element.tilte}} </td>
  </ng-container>

  <!-- Body Column -->
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Body </th>
    <td mat-cell *matCellDef="let element"> {{element.body}} </td>
  </ng-container>


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

我希望在表格中显示邮政服务的数据

1 个答案:

答案 0 :(得分:0)

因为在显示的列中,第三列是“ body”:

displayedColumns: string[] = ['id', 'title', 'body'];

但是在HTML中,第三列def为“重量”:

  <!-- Body Column -->
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Body </th>
    <td mat-cell *matCellDef="let element"> {{element.body}} </td>
  </ng-container>

解决方案:

  1. 从matColumnDef =“ weight”更改为matColumnDef =“ body”