尝试将数据放入物料表。
我制作了具有ID,日期等字段的block.model,在我确实请求的data.service中使用了func getAllBlock()(返回Block [])。它可以在app.component.html(我尝试过)中使用。
文档list.component.ts
import { MatTableDataSource } from '@angular/material/table';
import { DataService } from '../data.service';
import { Block } from '../models/block.model';
@Component({
selector: 'app-document-list',
templateUrl: './document-list.component.html',
styleUrls: ['./document-list.component.sass']
})
export class DocumentListComponent implements OnInit {
blocks: Block[];
//DataSource and columns for DataTable
displayedColumns: string[] = ['Id', 'Date', 'Data', 'Hash', 'PreviousHash'];
dataSource = new MatTableDataSource<Block>(this.blocks);
//Filter (search)
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
constructor(private dataService: DataService) { }
ngOnInit(){
return this.dataService.getAllBlock()
.subscribe(data => this.blocks = data);
}
}
文档list.component.html
<div class="content-table">
<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!-- ID Column -->
<ng-container matColumnDef="Id">
<th mat-header-cell *matHeaderCellDef>ID</th>
<td mat-cell *matCellDef="let element"> {{element.Id}} </td>
</ng-container>
<!-- Date Column -->
<ng-container matColumnDef="Date">
<th mat-header-cell *matHeaderCellDef>Timestamp</th>
<td mat-cell *matCellDef="let element"> {{element.Date}} </td>
</ng-container>
<!-- Data Column -->
<ng-container matColumnDef="Data">
<th mat-header-cell *matHeaderCellDef>Data</th>
<td mat-cell *matCellDef="let element"> {{element.Data}} </td>
</ng-container>
<!-- Hash Column -->
<ng-container matColumnDef="Hash">
<th mat-header-cell *matHeaderCellDef>Hash</th>
<td mat-cell *matCellDef="let element"> {{element.Hash}} </td>
</ng-container>
<!-- Previous Hash -->
<ng-container matColumnDef="PreviousHash">
<th mat-header-cell *matHeaderCellDef>PrevHash</th>
<td mat-cell *matCellDef="let element"> {{element.PreviousHash}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
我不知道如何将数据插入表中。请帮助我。我做错什么或哪里出了问题?附:对不起,英语不好
最初this.blocks
是undefined
。订阅dataSource
之后,一旦定义了this.blocks
,就需要创建getAllBlock
。在这里使用return
也没有意义,因为您只是从subscribe
获取数据。因此,只需简单地调用getAllBlock
。
这里是现在的样子。
dataSource: MatTableDataSource<Block>;
ngOnInit() {
this.dataService.getAllBlock().subscribe(data => {
this.blocks = data
this.dataSource = new MatTableDataSource<Block>(this.blocks);
});
}