當我嘗試對可觀察陣列進行排序時,我無法獲得物件。
我想按“Localite”對其進行排序,我獲得的結果只是“Localite”,不再是完整的物件。
我不明白為什么。
我的 Json 檔案如下所示:
{
A[
Code_Postal: ...
Localite: ...
Sous_commune: ...
Commune_principale: ...
]
B[
Code_Postal: ...
Localite: ...
Sous_commune: ...
Commune_principale: ...
]
C[
...
]
...
}
我的界面是這樣的:
export interface Communes{
Code_Postal : number;
Localite : string;
Sous_commune : string;
Commune_principale: string;
}
對 json 檔案進行排序的函式如下所示:
getCommunes(prov: string): Observable<Communes[]> {
return this.jsonService.getData(this.zipCodesFile)
.pipe(
map((response: any) =>
response[prov].map((localite: Communes) => localite.Localite)
.sort((a: any, b: any) => {
return a.localeCompare(b, 'en', { sensitivity: 'base' });
})
),
)
}
TS檔案中函式的呼叫是這樣的:
loadCommunes(): void{
this.communes$ = this.apiService.getCommunes('Anvers');
}
在 html 檔案中,我希望能夠像這樣使用它:
<ul>
<li *ngFor="let commune of (communes$ | async)">{{commune.Code_Postal}} - {{commune.Localite}}</li>
</ul>
如何在對 json 檔案進行排序后檢索物件?
謝謝
uj5u.com熱心網友回復:
將您更改map為:
map((response: any) =>
response[prov]
.sort((a: Communes, b: Communes) => {
return a.Localite.localeCompare(b.Localite, 'en', { sensitivity: 'base' });
})
),
您在那里的陣列map正在將其更改為Localite值的陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/429978.html
