Angular多维对象CustomerRegistration类给firstname赋值报错如何解决
错误原因
你在CustomerRegistration类中仅声明了customer属性的类型结构,没有为其设置初始值。当你执行new CustomerRegistration()创建实例时,实例的customer属性默认是undefined,直接访问undefined.firstname就会触发你遇到的类型错误。
可行修复方案
- 方案1:在模型类中添加初始化逻辑
修改registration.ts,给customer设置默认初始值,不需要调整组件代码即可正常赋值:
export class CustomerRegistration{ // 直接给属性设置初始值 customer: { firstname : string; lastname : string; email: string; } = { firstname: '', lastname: '', email: '' } password: string = ''; }
- 方案2:在组件赋值前先初始化
customer对象
不需要修改模型类,在组件中给firstname赋值前,先给customer属性初始化符合结构的对象即可:
hello(){ // 先初始化customer属性 this.register.customer = { firstname: 'Karan', lastname: '', email: '' }; console.log(this.register); }
- 方案3:给模型类添加构造函数支持灵活初始化
如果后续需要在创建实例时就传入属性值,可以给类添加构造函数:
export class CustomerRegistration{ customer: { firstname : string; lastname : string; email: string; }; password: string; constructor(customer?: {firstname: string, lastname: string, email: string}, password?: string) { this.customer = customer ?? {firstname: '', lastname: '', email: ''}; this.password = password ?? ''; } }
创建实例时就可以直接传入初始值:
register = new CustomerRegistration({firstname: 'Karan', lastname: '', email: ''}, '自定义密码');
内容的提问来源于stack exchange,提问作者Karan Adhikari
相关产品推荐
相关产品推荐

