为什么我的数据没有填充到Angular材质表中

时间:2019-07-19 08:42:02

标签: angular angular-material

我正在尝试从服务器中获取数据以填充Angular Material数据表,但未显示任何内容。我不确定我的dataSource是否不正确或者我做错了什么。

我按照文档中的示例进行操作,以确保我做得正确并且到目前为止效果很好。接下来,我尝试从api获取数据并能够完成该任务。现在,我正在尝试从本地服务器获取数据,但没有任何显示。我在想什么/做错了

export interface Task {
    title: string;
    note:string;
}

服务

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable } from 'rxjs';
import { Task } from './task.model'

@Injectable({
  providedIn: 'root'
})
export class HttpService {
  private serviceUrl = "http://localhost:8000/tasks"
  // private serviceUrl = "https://jsonplaceholder.typicode.com/users"
  constructor(private _http:HttpClient) { }

  getTasks():Observable<Task[]> {
    return this._http.get<Task[]>(this.serviceUrl);
  }

组件

import { Component, OnInit, ViewChild } from '@angular/core';
import { HttpService } from './../../http.service';
import { Observable } from 'rxjs';
import { DataSource } from '@angular/cdk/collections';
import { MatTableDataSource, MatPaginator, MatSort, MatSortable, MatTable } from '@angular/material';
import { Task } from './../../task.model';


@Component({
  selector: 'trial',
  templateUrl: './trial.component.html',
  styleUrls: ['./trial.component.scss']
})
export class TrialComponent implements OnInit {
  dataSource = new MatTableDataSource<Task>();
  displayedColumns = ['title', 'note'];

  constructor(private _httpService:HttpService) { }

  ngOnInit() {
    this.getTask();
  }

  getTask(){
    this._httpService.getTasks().subscribe(data => {
      if(!data){
        return;
      }
      this.dataSource = new MatTableDataSource(data)
      console.log(this.dataSource)
    })
  }
}

我也尝试过这种方法。也许有人可以让我知道哪种是正确或更好的方法

import { Component, OnInit, ViewChild } from '@angular/core';
import { HttpService } from './../../http.service';
import { Observable } from 'rxjs';
import { DataSource } from '@angular/cdk/collections';
import { MatTableDataSource, MatPaginator, MatSort, MatSortable, MatTable } from '@angular/material';
import { Task } from './../../task.model';


@Component({
  selector: 'trial',
  templateUrl: './trial.component.html',
  styleUrls: ['./trial.component.scss']
})
export class TrialComponent implements OnInit {
  displayedColumns = ['title', 'note'];
  dataSource = new TasksDataSource(this._httpService);

  constructor(private _httpService:HttpService) { }

  ngOnInit() {
  }

}

export class TasksDataSource extends DataSource<any>{
  constructor(private _httpService:HttpService) {
    super();
  }

  connect():Observable<Task[]> {
    return this._httpService.getTasks();
  }

  disconnect(){}
}

HTML

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

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

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

  </table>

我的控制台未显示任何错误。希望有人可以提供帮助,因为我已经尝试了一段时间,而且越来越令人沮丧,你们知道这种感觉

2 个答案:

答案 0 :(得分:0)

尝试一下:

this.dataSource.data = data;

答案 1 :(得分:0)

您不需要实例化数据源对象。只需将Task []传递到mat-table。

一种更好的方法是使用async管道来避免订阅可观察的

@Component({
  selector: 'trial',
  templateUrl: './trial.component.html',
  styleUrls: ['./trial.component.scss']
})
export class TrialComponent implements OnInit {
  dataSource$: Observable<Task[]>;
  displayedColumns = ['title', 'note'];

  constructor(private _httpService:HttpService) { }

  ngOnInit() {
    this.dataSource$ = this.getTask();
  }

  getTask(){
    return this._httpService.getTasks().pipe(
        map((res) => res.tasks)
    );

  }
}

HTML

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

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

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

  </table>