简体   繁体   中英

How exactly works this service retrieving a JSON objects array? Why is not mapping on moel objects?

I am pretty new in Angular and I have a big doubt about how exctly this situation works:

Into my component code I have something like this:

orders: Order[];

ngOnInit() {

    this.ordersService.getAllOrders().then(orders => {
        this.orders = orders;
        console.log("RETRIEVED ORDERS: ", orders);
        this.loading = false;
});

As you can see firest I am defining an array of Order model objects.

Then into the ngOnInit() method I am retrieving this array using this getAllOrders() service method:

getAllOrders() {
    return this.http.get<any>('assets/json_mock/ordini.json')
        .toPromise()
        .then(res => <Order[]>res.data)
        .then(data => { return data; });
}

That basically retrieve the values from a JSON file.

Now...caming from Java I have some doubts about it works in Angular\TypeScript. My idea is that the objects defined inside my ordini.json file have to be mapped on Order model objects.

So this is my Order model interface:

export interface Referent {
  name?: string;
  surname?: string;
  role?: string;
}

export interface Company {
  name?: string;
  vat?: string;
  bu?: BU;
}

export interface BU {
  name?: string;
  code?: string;
}

export interface OrderDetails {
  dataInserimento?: Date;
  commesse?: Array<string>;
  identificativoContrattoHyperlink?: string;
  tipologiaContratto?: string;
  presenzaAQ?: string;
  identificativoAQHyperlink?: string;
  accordoQuadro?: string;
  importoContratto?: number;
  residuoAQ?: number;
  compagineDiAQ?: number;
  quotaPercentualeDiRTI?: number;
  tipologiaDiPartecipazione?: string;
  cig?: string;
  cliente?: string;
  vatCliente?: string
  clienteFinale?: string;
  vatClienteFinale?: string;
  dataSottoscrizioneContratto?: string;
  dataInizioAttivita?: Date;
  dataFineAttivita?: Date;
  statoOrdine?: string;

}

export interface Order {
  id?: number;
  name?: string;

  company?: Company;
  dettaglioOrdine?: OrderDetails;

}

So as you can see I have an Order intrface containing some fields (sometimes defined as other interface).

This is my JSON file content:

{
  "data": [
    {
      "id": 1,

      "referente": {
        "name": "Mario",
        "surname": "Rossi",
        "complete_name": "Mario Rossi",
        "role": "Operation Manager"
      },

      "company": {
        "name": "TEST S.p.A.",
        "VAT": "IT 03318271214",

        "BU": {
          "name": "Digital Solution",
          "code": "DS"
        }
      },

      "dettaglio_ordine": {
        "data_inserimento": "2020-08-08",


        "commessa": {
          "code": "AAA0001"
        },

        "identificativo_contratto_hyperlink": "LINK-ID-CONTRATTO-TEST",
        "tipologia_contratto": "ORDINE",
        "presenza_AQ": true,
        "identificativo_AQ_hyperlink": "LINK-AQ-TEST",
        "accordo_quadro": 12,
        "importo_contratto": 122000,
        "residuo_AQ": 20000,
        "compagine_di_AQ": "COMPAGINE-DI-AQ-TEST",
        "quota_percentuale_di_RTI": 20,
        "tipologia_di_partecipazione": "GARA PUBBLICA",
        "cig": "CIG-TEST-1",
        "cliente": "CLIENTE-TEST-1",
        "vat_cliente": "VAT-CLIENTE",
        "cliente_finale": "CLIENTE-FINALE-TEST-1",
        "vat_cliente_finale": "VAT-CLIENTE-FINALE",
        "data_sottoscrizione_contratto": "8/12/2020",
        "data_inizio_attivita": "2020-08-28",
        "data_fine_attivita": "2020-08-30",
        "stato_ordine": "CHIUSO"
      }
    },

    {
      "id": 2,

      "referente": {
        "name": "Mario",
        "surname": "Rossi",
        "complete_name": "Mario Rossi",
        "role": "Operation Manager"
      },

      "company": {
        "name": "DGS S.p.A.",
        "VAT": "IT 03318271214",

        "BU": {
          "name": "Cyber Security",
          "code": "CS"
        }
      },

      "dettaglio_ordine": {
        "data_inserimento": "2020-08-09",


        "commessa": {
          "code": "AAA0002"
        },

        "identificativo_contratto_hyperlink": "LINK-ID-CONTRATTO-TEST",
        "tipologia_contratto": "ORDINE",
        "presenza_AQ": false,
        "identificativo_AQ_hyperlink": "LINK-AQ-TEST",
        "accordo_quadro": 12,
        "importo_contratto": 122000,
        "residuo_AQ": 20000,
        "compagine_di_AQ": "COMPAGINE-DI-AQ-TEST",
        "quota_percentuale_di_RTI": 20,
        "tipologia_di_partecipazione": "GARA PUBBLICA",
        "cig": "CIG-TEST-2",
        "cliente": "CLIENTE-TEST-1",
        "vat_cliente": "VAT CLIENTE TEST",
        "cliente_finale": "CLIENTE-FINALE-TEST-2",
        "vat_cliente_finale": "VAT-CLIENTE-FINALE-TEST",
        "data_sottoscrizione_contratto": "8/12/2020",
        "data_inizio_attivita": "8/28/2020",
        "data_fine_attivita": "8/31/2020",
        "stato_ordine": "CHIUSO"
      }
    },

    {
      "id": 3,

      "referente": {
        "name": "Francesco Nicola",
        "surname": "Romano",
        "complete_name": "Francesco Nicola Romano",
        "role": "Operation Manager"
      },

      "company": {
        "name": "DGS S.p.A.",
        "VAT": "IT 03318271214",

        "BU": {
          "name": "Cyber Security",
          "code": "CS"
        }
      },

      "dettaglio_ordine": {
        "data_inserimento": "2020-08-10",


        "commessa": {
          "code": "AAA0002"
        },

        "identificativo_contratto_hyperlink": "LINK-ID-CONTRATTO-TEST",
        "tipologia_contratto": "ORDINE",
        "presenza_AQ": false,
        "identificativo_AQ_hyperlink": "LINK-AQ-TEST",
        "accordo_quadro": 12,
        "importo_contratto": 122000,
        "residuo_AQ": 20000,
        "compagine_di_AQ": "COMPAGINE-DI-AQ-TEST",
        "quota_percentuale_di_RTI": 20,
        "tipologia_di_partecipazione": "GARA PUBBLICA",
        "cig": "CIG-TEST-3",
        "cliente": "CLIENTE-TEST-3",
        "vat_cliente": "XXX123",
        "cliente_finale": "CLIENTE-FINALE-TEST-3",
        "vat_cliente_finale": "YYY321",
        "data_sottoscrizione_contratto": "8/12/2020",
        "data_inizio_attivita": "8/28/2020",
        "data_fine_attivita": "8/31/2020",
        "stato_ordine": "CHIUSO"
      }

    }
  ]
}

Basically this is an array of objects. My original idea is that every JSON objects defined in the array in the.json file have to be perfectly mapped on an object described by the Order model interface, because in my component I defined my orders variable as an array of Order :

orders: Order[];

but it seems that it is not working in this way.

My service class correctly retrive the information returning an array but this array seems contains the JSON object and not the Order fields.

Why? What am I missing? What is the correct way to map a JSON object on a model object? And moreover is it correct or in Angular could be acceptable using this JavaScrip\JSON object as a model object avoiding this step?

Typescript does not modify your object. the types are only used to better understand how data is shaped and to prevent errors.

So in this line:

   .then(res => <Order[]>res.data)

You simply tell typescript "the content of res.data is of type Order[]. Consider them as that from now on". It's up to you to define the proper type.

If you need to map your json response to match your type, what you need to do is:

  • Define the resulting type ( Order ) and a type representing the data you retrieve from api ( ApiOrder )

  • Declare a method to perform the transformation

const transformOrder = (apiOrder: ApiOrder): Order => {
 return { .. your order object ... }
}
  • Perform the transformation when you receive the data
.then(res => <ApiOrder[]>res.data)
.then(data: ApiOrder[] => { return data.map(transformOrder); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM