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

I play with Angular2, and was hoping that 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 place days / hours in their own facility, how could this be achieved?

(eg,...)

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

and then the http get request will remain the same as shown 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 request to get something like:

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

Hope someone can help! I try to look back, but have not come across anything that might help.

+4
source share
1 answer

Something like that

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

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

Source: https://habr.com/ru/post/1660945/


All Articles