How to define a nested object within model? (angular2/typescript)

confusedandenthused picture confusedandenthused · Nov 16, 2016 · Viewed 25k times · Source

I'm playing around with Angular2, and was hoping someone could offer some advice on how to achieve this;

For example, if my model currently looks like this for an employee:

export class Employee {
    constructor(
        public firstName: string,
        public lastName: string,
        public email: string,
        public days: string,
        public hours: string, 
    ){}
}

and I want to to place days/hour into their own object, how could that be achieved?

(i.e like..)

public availability: {
        public days: string,
        public hours: string
},

and then would the http get request stay the same like below?

getEmployees() {
      return this.http.get('...')
             .map((response: Response) => {
                 const data = response.json().obj;
                 let objs: any[] = [];

                 for(let i = 0; i < data.length; i++) {
                     let employee = new Employee(
                     data[i].firstName,
                     data[i].lastName, 
                     data[i].email, 
                     data[i].availability.days,
                     data[i].availability.hours
                     );

                     objs.push(employee)
                 }
                 return objs
             })
          }

Just to clarify, I would like my get request to return something like;

var obj = {
    firstName: "test",
    lastName: "test",
    email: "test",
    availability: {
      days: "test",
      hours: "test"
    }
  }

Hope someone can help out! I'm tried to look around, but haven't come across anything that can help.

Answer

Michael picture Michael · Nov 16, 2016

Something like this

export class Employee {
    constructor(
        public firstName: string,
        public lastName: string,
        public email: string,
        public availability: Availability // refer to type Availability  below
    ){}
}

export class Availability {
    constructor(
        public days: string,
        public hours: string
    ){}
}

Http get request should stay the same, then change on how you create new instance of employee

let employee = new Employee(
    data[i].firstName,
    data[i].lastName,
    data[i].email,
    new Availability(
          data[i].availability.days,
          data[i].availability.hours
    )
);