我尝试在角度材料表组件中显示来自 json 文件的数据,但我不能。
app.component.ts
ELEMENT_DATA: Itype[];
displayedColumns: string[] = ['dechets.bouteille_plastique'];
dataSource = new MatTableDataSource<Itype>(this.ELEMENT_DATA); // probleme is here
constructor(private authService: AuthenticationService) { }
ngOnInit() {
this.getAllDetails();
}
public getAllDetails() {
let resp = this.authService.getDetails();
resp.subscribe(report => this.dataSource.data=report as Itype[])
}
界面
export interface Itype {
type_collecte: string;
dechets: {
bouteille_plastique: number;
}
}
json.file
{
"type collecte": "reccurente",
"dechets": {
"bouteille_plastique": 2.9,
},
},
我不知道我在 html 中是否做对了
html
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!-- Position Column -->
<ng-container matColumnDef="dechets.bouteille_plastique">
<th mat-header-cell *matHeaderCellDef>Type de dechets</th>
<td mat-cell *matCellDef="let element">{{element.dechets.bouteille_plastique}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
答案 0 :(得分:0)
正如您提供的评论所指出的:“属性 'ELEMENT_DATA' 在初始化之前使用”,这意味着 ELEMENT_DATA 在用于定义数据源时未初始化。
您只需要将类中的 ELEMENT_DATA 定义更改为:
ELEMENT_DATA: IType[] = [];
这样当组件被实例化时,它可以使用空数组作为值来初始化 dataSource 对象。