![](/img/trans.png)
[英]How to populate nested json data to angular material drop down list
[英]how to get data from nested json in angular material tables ? - ANGULAR
我試圖從本地主機獲取數據,但是當它涉及不同的結構時,我無法理解如何獲取數據用戶的這些數據。 有什么幫助嗎?
這就是我試圖接近但失敗並得到錯誤錯誤的方式:找不到ID為“_id”的列。
Json 文件
{
"message": "Handling GET requests to User",
"dataUser": [
{
"CountLike": 15,
"CountShare": 26,
"id": "5edb6d50d77987442cf1d7ed",
"Name": "Andy",
"Point": 40
}
]
}
這是我的 servise.ts 文件
getUsers() {
return this.http.get('http://localhost:3000/surveys');
}
這是我的 html 文件
<mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="dataUser _id">
<th mat-header-cell *matHeaderCellDef>ID</th>
<td mat-cell *matCellDef="let element">
{{ element.dataUser._id }}
</td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="dataUser CountLike">
<th mat-header-cell *matHeaderCellDef>Like</th>
<td mat-cell *matCellDef="let element">
{{ element.dataUser.CountLike }}
</td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="dataSurvey CountShare">
<th mat-header-cell *matHeaderCellDef>Share</th>
<td mat-cell *matCellDef="let element">
{{ element.dataUser.CountShare }}
</td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="dataUser Point">
<th mat-header-cell *matHeaderCellDef>Point</th>
<td mat-cell *matCellDef="let element">
{{ element.dataUser.Point }}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr
mat-row
*matRowDef="let row; columns: displayedColumns"
(click)="selection.toggle(row)"
></tr>
</mat-table>
這是我的 component.ts 文件忽略我如何在接口 xD 上輸入名稱
export interface Userstructure {
_id: string;
CountLike: string;
CountShare: string;
Point: string;
}
export interface UserMain {
message: string;
dataUser: Userstructure[];
}
@component
displayedColumns: string[] = [
'_id',
'CountLike',
'CountShare',
'Point',
];
users: Userstructure[];
dataSource;
user;
selection = new SelectionModel<Userstructure>(true, []);
ngOnInit(): void {
console.log(this.users);//this return 'undefined' on console.
this.surveyService.getUsers().subscribe((users: Userstructure[]) => {
this.users = users;
this.dataSource = new MatTableDataSource(users);
});
}
首先,DataSource 需要一個對象數組,並且您為它提供了 object(基於您提供的示例 Json)。 因此,您只想使用響應的dataUser
部分。
this.surveyService.getUsers().subscribe((users: Userstructure[]) => {
this.users = users.dataUser;
this.dataSource = new MatTableDataSource(users.dataUser);
});
}
第二件事 - displayColumns 名稱必須與matColumnDef
中的displayedColumns
名稱匹配。 此外,您不希望在列名中添加任何空格 - 這些都被轉換為 id 和 css 類,因此您可能希望它們保持簡短和簡單。 只需從列名中刪除dataUser
部分(注意 - 也刪除空格)。 這應該可以解決您最初的問題 - 尚未檢查代碼的 rest,但這應該會讓您走上正軌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.