gpt4 book ai didi

angular - 如何在模型中定义嵌套对象? (angular2/ typescript )

转载 作者:太空狗 更新时间:2023-10-29 17:30:09 31 4
gpt4 key购买 nike

我正在玩 Angular2,希望有人能就如何实现这一目标提供一些建议;

例如,如果我的模型当前对于员工看起来像这样:

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

我想将天数/小时放入他们自己的对象中,这怎么可能实现?

(即喜欢..)

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

然后 http get 请求会像下面一样保持不变吗?

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

澄清一下,我希望我的 get 请求返回类似的东西;

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

希望有人能帮帮忙!我试着环顾四周,但没有发现任何可以提供帮助的东西。

最佳答案

类似这样的东西

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 请求应该保持不变,然后改变你创建新员工实例的方式

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

关于angular - 如何在模型中定义嵌套对象? (angular2/ typescript ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633688/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com