0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Good answer. Consider removing the I prefix.
Thanks Haddad. I edited the interface name to PascalCase.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.