我很難嘗試通過角度引導表迭代從 api 獲取的資料。從第一種方法開始,我將資料映射到在下面的函式中宣告并初始化的prsnl變數:prsnl: any
getAllPersnlValues(data) {
return this.persnlService.getPersnl(data)
.pipe(
map((response) => response)
).subscribe((res) => {this.prsnl = res; console.log('prsnl', this.prsnl)});
}
在 Html 方面,我有:
<table >
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">FULL NAME</th>
</tr>
</thead>
<tbody>
<tr *ngFor = "let pr of prsnl">
<th scope="row">1</th>
<td>{{pr.result.fullName}}</td>
</tr>
</tbody>
</table>
因為 api 的回應是物件的物件,如下圖所示:

正如您在控制臺上看到的,api 回應已正確分配給 getAllPersnlValues() 方法中的 prsnl 變數,但在表中迭代它失敗,因為表仍然為空。
然后我明白我需要將作為物件物件的 prsnl 型別轉換為物件陣列,以便 *ngFor 可以執行迭代,我現在使用 keyval fromKeyValuePipe將 api 的回應轉換為陣列,如您所見在下面的代碼中:
getAllPersnlValues(data) {
console.log('data', data);
return this.persnlService.getPersnl(data)
.pipe(
map((response) => {
if(typeof response !== 'undefined') this.keyval.transform(response)
})).subscribe((res) => {this.prsnl = res; console.log('prsnl', this.prsnl)})
}
但是這樣做會導致專案無法編譯,并且只有在我從 app.module.ts 中洗掉 KeyValuePipe 匯入時才會編譯,并且我意識到 subscribe() 函式不會 console.log this.prsnl值。然后,我如何才能使回應成為物件的物件并將其顯示在表格中。我將非常感謝您為解決這一障礙提供的幫助。提前致謝。
uj5u.com熱心網友回復:
*ngFor您正在嘗試使用本機不支持的指令迭代物件。你需要使用keyvalue管道來做到這一點。
但是看到您的日志,所需的陣列包含在result屬性中。所以嘗試以下
<tr *ngFor = "let res of prsnl?.result">
<th scope="row">1</th>
<td>{{ res?.fullName }}</td>
</tr>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478923.html
下一篇:序列化可序列化/序列化元素的向量
