How to Observable map nested json objects with different property names - Angular

后端 未结 1 1071
無奈伤痛
無奈伤痛 2021-01-26 15:26

I have an json result which has nested objects. I need to cast them to my custom objects ( prime ng tree table json) which have different property names than the json result.

相关标签:
1条回答
  • 2021-01-26 15:46

    I'm assuming that the 'json result' comes from backend call. So the best and easiest way would be to map the observable to your destination format.

    1. You should use HttpClient (the call to backend will return you an Observable) -> https://angular.io/guide/http

    2. Create an interface, that will describe json object field names (let's call it PersonalDetails):

      export interface PersonalDetails {
       brinname: string,
       aantalPersonen: string,
       ...
    }
    

    There can be several interfaces (the json object is really big, so it might be good to split it and create other interfaces, that will be nested inside the first one).

    1. Create interface for 'prime ng tree table json' => same as above, let's call it PrimeNgTableData

    2. Create a function, that will take a parameter of type 'PersonalDetails' (from point 2.) and will cast it to second interface PrimeNgTableData (from point 3.). Let's name that function like that:

      export function asPrimeNgTableData(personalDetails: PersonalDetails): PrimeNgTableData {
       return {
          ...
        }
      }
    
    1. Create new observable, that will keep the primeNgTableData values:
       private personalDetails$: Observable<PersonalDetails> = this.someServiceThatCallsHttp.getPersonalDetails();
    
       private primeNgTableData$: Observable<PrimeNgTableData> = this.personalDetails$.pipe(
          map((personalDetails: PersonalDetails) => asPrimeNgTableData(personalDetails))
        );
    
    1. Use primeNgTableData$ in your html template (let's assume, that the html tag that you wanna use is called 'ngTable', and it gets 'data' input, that has a type of PrimeNgTableData
      <ngTable [data]="primeNgTableData$ | async"> 
        ....
      </ngTable>
    
    0 讨论(0)
提交回复
热议问题