简体   繁体   English

如何将数据从JSON API传递到TypeScript模型

[英]How to pass data from JSON API to TypeScript models

In my services I have to pass the information served by my JSON api to my models. 在我的服务中,我必须将JSON api提供的信息传递给我的模型。 What is the best way to do this? 做这个的最好方式是什么?

At the moment I am doing this: 目前,我正在这样做:

import { Attachment } from '.';

export class Contact {
  id: number;
  attachments: Attachment[] = [];

  static fromJSON(data) {
    let contact = new Contact();
    contact.id = data.id;

    // Attachments?
    for(let attachment of data.attachments) {
      contact.attachments.push( Attachment.fromJSON(attachment) );
    }
    return contact;
  }
}

}

Are there better ideas? 有更好的主意吗?

If I understand well, you want to get the information that comes from a JSON string returned by a service. 如果我理解得很好,您想获取来自服务返回的JSON字符串的信息。

Let said that you have the following to get the JSON. 让我们说您具有以下获取JSON的条件。

   that.db.getTodoListFromServer(this)
                .done(msg => {
                    if (msg != undefined) {
                        //in msg you have your JSON object
                 })
                .fail(msg => {
                 });

In this point you can do two things 在这一点上,您可以做两件事

  1. If you know the class structure of the JSON string you can pass directly element by element to your model as you done in your solution. 如果您知道JSON字符串的类结构,则可以像在解决方案中一样直接将元素逐个传递给模型。

2.- Create a interface with the structure of the JSON object returned (typescript support interfaces). 2.-使用返回的JSON对象的结构创建一个接口(打字稿支持接口)。 In the example below we created a interface IToDoModel. 在下面的示例中,我们创建了一个接口IToDoModel。 Because we know that the JSON returned has the same structure that our interface, no error happen when we assigned the JSONreturn to the interface. 因为我们知道返回的JSON与接口具有相同的结构,所以当我们将JSONreturn分配给接口时不会发生错误。

 export interface ToDoModel {
        Id: number;
        ToDo: string;
    }

...  

that.db.getTodoListFromServer(this)
            .done(msg => {
                 if (msg != undefined) {
                     //this json return a list of IToDoModel
                     var todo: Array<ToDoModel> = msg;
              })
            .fail(msg => {
                     //Manage Error   
             });

I hope this help you 希望对您有帮助

The simplest way is cast attachments to Array<Attachment> directly. 最简单的方法是直接将附件转换为Array<Attachment>

import { Attachment } from '.';

export class Contact {
  id: number;
  attachments: Attachment[] = [];

  static fromJSON(data) {
    let contact = new Contact();
    contact.id = data.id;

    // cast attachments json to `Array<Attachment>`.
    contact.attachments = <Array<Attachment>>data.attachments;

    return contact;
   }
 }
}

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

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