我正在我的 Angular 專案中使用 API,我得到了這個 JSON:
{
"id": 16,
"poste": "ameur taboui",
"desciption": "f",
"service": "f",
"creationDate": "2022-10-13",
"updatedDate": "2022-10-24",
"active": true,
"personnelPosteListe": {
"id": 1,
"nomPersonnel": "ADMIN",
"prenomPersonnel": "ADMIN",
"matricule": 2564,
"dateNaissance": "2022-07-26",
"cin": 7858585,
"telephone": 2554884,
"adresse": "tunis",
"dateAff": "2022-07-26",
"dateFinAff": "2022-07-26",
"typeContrat": "test",
"champInterim": "f",
"active": true
},
},
我嘗試在我的 HTML 中訪問 personPosteListe,但出現錯誤
錯誤:找不到“object”型別的不同支持物件“[object Object]”。NgFor 僅支持系結到 Iterables,例如 Arrays。對此有什么幫助嗎?這是我的 TS 檔案:
onGetPosteListeByID() {
this.grhService
.getPosteListeById(this.id)
.pipe(takeUntil(this.onDestroy$))
.subscribe(
(data) => {
this.poste = data;
console.log(this.poste);
},
(err) => {
console.log(err);
}
);
}
}
這是我的 HTML:
<table class="table table-striped table-hover table-bordered text-center table-centre table-res">
<thead class="thead-light">
<tr>
<th> {{"Nom" | translate }} </th>
<th> {{"Prénom" | translate }}</th>
<th> {{"Type de contrat" | translate}}</th>
<th> {{"Matricule" | translate }}</th>
<th> {{"Telephone" | translate }}</th>
</tr>
<tr *ngFor="let b of poste?.personnelPosteListe ; trackBy: trackByMethod ">
<td> {{ b?.nomPersonnel}}</td>
<td> {{ b?.prenomPersonnel }}</td>
.
.
.
.
</tr>
</thead>
</table>
uj5u.com熱心網友回復:
這里的錯誤是因為你的 json 中的 poste?.personnelPosteListe 是一個物件,而 ngfor 只能接受陣列。將此監聽轉換為 js 端或服務器端的陣列
uj5u.com熱心網友回復:
發生錯誤是因為 personPosteListe 在您的情況下是一個物件,而 ngFor 在此處需要一個陣列。
這可能是一個服務器問題,如果 personPosteListe 的長度為 1,您只會得到一個物件而不是陣列。一些 API 的行為是這樣的。您可以強制它成為客戶端的陣列:
onGetPosteListeByID() {
this.grhService.getPosteListeById(this.id).pipe(
map(data => {
if(Array.isArray(data.personnelPosteListe)) return data;
return { ...data, personnelPosteListe: [data.personnelPosteListe]};
}),
takeUntil(this.onDestroy$),
).subscribe(
(data) => {
this.poste = data;
console.log(this.poste);
},
(err) => {
console.log(err);
}
);
}
}
uj5u.com熱心網友回復:
我已閱讀您的文章,您可以使用KeyValuePipe獲取 'nomPersonnel' 和 'prenomPersonnel'
<div *ngFor="let item of object | keyvalue">
{{item.key}}:{{item.value}}
</div>
哦,你也可以看看這個帖子,也許還有其他好主意
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522010.html
