我一直在寻找解决方案,但是我的代码似乎超出了标准的“将对象推入数组”范围。
我有一个接口,它使用另一个接口作为数组键入“年”属性:
export interface IUser {
Nickname: string;
FirstName: string;
LastName: string;
Email: string;
EmergencyContact: string;
EmergencyNumber: string;
Year: Array<IYear>;
IsTeacher: boolean;
IsAdmin: boolean;
Uid: string;
}
export interface IYear {
CalendarYear: string;
PassType: string;
UserItinerary: IItinerary;
WaiverStatus: boolean;
Guests: Array<IGuest>;
SignupDate: string;
}
在某个时候,我将一些formGroup数据传递给IYear类型的属性:
user: IUser = <IUser>{};
createUser(
firstName: string,
lastName: string,
email: string,
uid: string,
isTeacher: boolean,
passType: string) {
const year: IYear = {
CalendarYear: this.calendarYear,
PassType: passType,
UserItinerary: {} as IItinerary,
WaiverStatus: false,
Guests: [],
SignupDate: this.dateTime
}
this.user.FirstName = firstName;
this.user.LastName = lastName;
this.user.Email = email;
this.user.Uid = uid;
this.user.IsTeacher = isTeacher;
this.user.IsAdmin = false;
this.user.Year.push(year);
return this.user;
}
问题是,当我尝试将createUser内的'year'属性传递到'this.user.Year'数组时,出现错误
无法读取未定义的属性“ push”
我尝试通过键显式传递值:
this.user.Year['CalendarYear'] = year.CalendarYear;
但是那没有用。有人可以在这里指出我的错误吗?
答案 0 :(得分:3)
在将对象推入用户对象之前,应将用户对象中的Year数组初始化为空。
this.user.Year = [];
然后
this.user.Year.push(year);
答案 1 :(得分:2)
出现错误的原因是,您必须首先初始化一个数组,然后可以push()
为其赋值。
IUser
初始化一个新的year = [{your year}]
,然后然后将更多的值推入其中。IUser
对象,然后然后将值推入该对象。答案 2 :(得分:1)
您已经在使用数组之前对其进行了初始化。
user: IUser = <IUser>{};
createUser(
firstName: string,
lastName: string,
email: string,
uid: string,
isTeacher: boolean,
passType: string) {
const year: IYear = {
CalendarYear: this.calendarYear,
PassType: passType,
UserItinerary: {} as IItinerary,
WaiverStatus: false,
Guests: [],
SignupDate: this.dateTime
}
this.user.FirstName = firstName;
this.user.LastName = lastName;
this.user.Email = email;
this.user.Uid = uid;
this.user.IsTeacher = isTeacher;
this.user.IsAdmin = false;
this.user.Year=[];
this.user.Year.push(year);
return this.user;
}
答案 3 :(得分:0)
您需要确保Year
存在于用户对象上,并且CalendarYear
也存在于Year
对象上