简体   繁体   中英

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. 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.

Let said that you have the following to get the 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.

2.- Create a interface with the structure of the JSON object returned (typescript support interfaces). In the example below we created a interface 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.

 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.

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;
   }
 }
}

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