简体   繁体   English

该服务如何检索 JSON 对象数组? 为什么不映射到 moel 对象上?

[英]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:我是 Angular 的新手,我很怀疑这种情况的具体情况:

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.如您所见,我首先定义了一个Order model 对象数组。

Then into the ngOnInit() method I am retrieving this array using this getAllOrders() service method:然后进入ngOnInit()方法,我使用这个getAllOrders()服务方法检索这个数组:

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.这基本上是从 JSON 文件中检索值。

Now...caming from Java I have some doubts about it works in Angular\TypeScript.现在...来自 Java 我对它在 Angular\TypeScript 中的工作有些怀疑。 My idea is that the objects defined inside my ordini.json file have to be mapped on Order model objects.我的想法是我的ordini.json文件中定义的对象必须映射到Order model 对象上。

So this is my Order model interface:所以这是我的订单model 界面:

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).正如您所看到的,我有一个包含一些字段(有时定义为其他接口)的Order接口。

This is my JSON file content:这是我的 JSON 文件内容:

{
  "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 :我最初的想法是,.json 文件中的数组中定义的每个 JSON 对象都必须完美映射到Order model 接口描述的 object 上,因为在我的组件中,我将orders变量定义为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.我的服务 class 正确检索返回数组的信息,但该数组似乎包含 JSON object 而不是订单字段。

Why?为什么? What am I missing?我错过了什么? What is the correct way to map a JSON object on a model object? map JSON model object object 的正确方法是什么? And moreover is it correct or in Angular could be acceptable using this JavaScrip\JSON object as a model object avoiding this step?而且它是正确的还是在 Angular 中使用这个 JavaScrip\JSON object 作为 model object 避免这一步?

Typescript does not modify your object. the types are only used to better understand how data is shaped and to prevent errors. Typescript不会修改您的 object。这些类型仅用于更好地了解数据的形状并防止错误。

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".您只需告诉 typescript “res.data 的内容是 Order[] 类型。从现在开始将它们视为此类”。 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:如果您需要 map 您的 json 响应以匹配您的类型,您需要做的是:

  • Define the resulting type ( Order ) and a type representing the data you retrieve from api ( ApiOrder )定义结果类型 ( Order ) 和表示您从 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); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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