Home > database >  Get object when sorting an Observable array
Get object when sorting an Observable array

Time:02-22

I can't get an object when I try to sort an Observable Array.

I want to sort it by "Localite" and the result I obtain is only "Localite" and no more the complete object.

I don't understand why.

My Json file looks like this :


{
    A[
       Code_Postal: ...
       Localite: ...
       Sous_commune: ...
       Commune_principale: ...
     ]
    B[
      Code_Postal: ...
      Localite: ...
      Sous_commune: ...
      Commune_principale: ...
     ]
    C[
      ...
     ]
    ...
}

My interface is like :


export interface Communes{
    Code_Postal       : number;
    Localite          : string;
    Sous_commune      : string;
    Commune_principale: string;
}

The function who sort the json file looks like this :


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' });
            })
        ),
      )
  }

The calling of the function in TS file is like this :


  loadCommunes(): void{
  this.communes$ =  this.apiService.getCommunes('Anvers');
  }

In the html file I want be able to use it like this :


  <ul>
  <li *ngFor="let commune of (communes$ | async)">{{commune.Code_Postal}} - {{commune.Localite}}</li>
</ul>

How can I retrieve an object after sorting of the json file?

Thanks

CodePudding user response:

change your map to:

    map((response: any) =>
      response[prov]
        .sort((a: Communes, b: Communes) => {
          return a.Localite.localeCompare(b.Localite, 'en', { sensitivity: 'base' });
        })
    ),

the array map you had on there is changing it into an array of the Localite value.

  • Related