confusedandenthused confusedandenthused - 16 days ago 7
TypeScript Question

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

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

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
    )
);
Comments